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?

2

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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 () } 

Comments

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 () } 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.