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>(){ "elem开发者_开发知识库ent1", "element2" };
foreach (var value in list)
{
// do stuff ()
}
But how can I access the index-value in the C# version?
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
)
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 ()
}
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 ()
}
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
精彩评论