views:

126

answers:

4

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?

+1  A: 

Found multiple solutions on: http://stackoverflow.com/questions/521687/c-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)

Bob Fanger
Jared's solution at that link is very good.
Iain Galloway
+1  A: 

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
+1  A: 

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
+1  A: 

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

Andriy Shvay