1

In PHP I can do this:

$list = array("element1", "element2");
foreach ($list as $index => $value) {
  // do stuff
}

In C# i can write:

var list = new List<string>(){ "element1", "element2" };
foreach (var value in list) 
{
  // do stuff ()
}

But how can I access the index-value in the C# version?

Bob Fanger
  • 28,949
  • 7
  • 62
  • 78
  • possible duplicate of [C# newbie: find out the index in a foreach block](http://stackoverflow.com/questions/1192447/c-newbie-find-out-the-index-in-a-foreach-block) – adrianbanks Oct 21 '10 at 09:09
  • It's a duplicate of http://stackoverflow.com/questions/521687/c-foreach-with-index, but the target audience of this question is (ex)php-programmers instead of Ruby/Python programmers) – Bob Fanger Oct 21 '10 at 14:00

4 Answers4

2

Found multiple solutions on: foreach with index

I liked both JarredPar's solution:

foreach ( var it in list.Select((x,i) => new { Value = x, Index=i }) )
{
    // do stuff (with it.Index)      
}

and Dan Finch's solution:

list.Each( ( str, index ) =>
{
    // do stuff 
} );

public static void Each<T>( this IEnumerable<T> ie, Action<T, int> action )
{
    var i = 0;
    foreach ( var e in ie ) action( e, i++ );
}

I chose Dan Finch's method for better code readability.
(And I didn't need to use continue or break)

Community
  • 1
  • 1
Bob Fanger
  • 28,949
  • 7
  • 62
  • 78
1

I'm not sure it's possible to get the index in a foreach. Just add a new variable, i, and increment it; this would probably be the easiest way of doing it...

int i = 0;
var list = new List<string>(){ "element1", "element2" };
foreach (var value in list) 
{
  i++;
  // do stuff ()
}
alex
  • 3,710
  • 32
  • 44
1

If you have a List, then you can use an indexer + for loop:

var list = new List<string>(){ "element1", "element2" };
for (int idx=0; idx<list.Length; idx++) 
{
   var value = list[idx];
  // do stuff ()
}
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
1

If you want to access index you should use for loop

for(int i=0; i<list.Count; i++)
{
   //do staff()
}

i is the index

Ash
  • 1,924
  • 1
  • 13
  • 14