0

I have a list in my program, defined as such: List<String> myList = new List<String>();

I also have a foreach loop, getting an item out of it:

foreach (String item in myList)
{
    ...
}

In the above loop, I want to figure out what the index of item is in myList. How can I do this?

Servy
  • 193,745
  • 23
  • 295
  • 406
Will Eccles
  • 365
  • 1
  • 4
  • 14
  • 5
    If you are going to need the item's index, why not use a `for` loop instead of a `foreach` loop? – Golden Dragon Apr 09 '14 at 19:14
  • @GoldenDragon Now I feel like an idiot... Why didn't I think of that? It's how I'd do it in ruby and such... Thanks, man! – Will Eccles Apr 09 '14 at 19:15
  • `List n = new List(); foreach (string s in n) { int index= n.IndexOf(s, 0); }` – HackerMan Apr 09 '14 at 19:22
  • With a string there can be a difference. With string IndexOf is the first match so even with {"one","two","one"}. The last IndexOf would be 0. Use a for or a counter. – paparazzo Apr 09 '14 at 19:33

0 Answers0