views:

119

answers:

4

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.

+9  A: 

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.

Tomas Petricek
+3  A: 

Just switch from Find(...) to FindIndex(...)

List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B" }; 
currentPostalCode = "A2B"; 
postalCodes.FindIndex(s => s == currentPostalCode);
Daniel Renshaw
+1  A: 

try this:

int indexofA2B = postalCodes.IndexOf("A2B");
Luiscencio
A: 

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();
Chad