I'm trying to get the next item in a list of strings (postal codes). Normally I'd just foreach till I find it and then get the next in the list but I'm trying to be a bit more intuitive and compact than that (more of an exercise than anything).
I can find it easily with a lambda:
List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B" };
currentPostalCode = "A2B";
postalCodes.Find((s) => s == currentPostalCode);
Which is cool and all, and I properly get "A2B", but I'd prefer the index than the value.
You can use the IndexOf
method (this is a standard method of the generic List<T>
class):
List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B" };
currentPostalCode = "A2B";
int index = postalCodes.IndexOf(currentPostalCode);
For more information, see MSDN .
Just switch from Find(...) to FindIndex(...)
List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B" };
currentPostalCode = "A2B";
postalCodes.FindIndex(s => s == currentPostalCode);
尝试这个:
int indexofA2B = postalCodes.IndexOf("A2B");
what about something like
List<string> names = new List<string> { "A1B", "A2B", "A3B" };
names.Select((item, idx) => new {Item = item, Index = idx})
.Where(t=>t.Index > names.IndexOf("A2B"))
.FirstOrDefault();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.