views:

260

answers:

3

Is there a way in a for each to get the row index ?

Example :

int rowIndex = 0;
foreach (int a in numbers)
{
    // Manipulation
    rowIndex++;
}

What I would like to have

foreach (int a in numbers)
{
    a.RowIndex;
}

Is there a quick way of doing it ? Maybe with the use of extension methods ?

+4  A: 

Try the following

foreach ( var item in numbers.Select( (x,i) => new { Index = i, Value = x })) {
  var index = item.Index;
  var value = item.Value;
  ...
}

There is an overload of select which passes down the index of the item. This code will create a new anonymous type for every item which includes both the index and the value.

Here's an alternate way which makes the syntax slightly more readable.

public static void ForEach<T>(this IEnumerable<T> source, Action<T,int> del) {
  int i = 0;
  foreach ( var cur in source ) { 
    del(cur, i);
    i++;
  }
}

numbers.ForEach( (x,i) =>
{
  // x is the value and i is the index
}

This doesn't add a whole lot over the define a local and increment it manually solution. Is there a particular reason you don't want to do it that way?

JaredPar
This does the job more in the style of the syntax the asker seems to want, though to me it seems a bit ugly, and not really adding extra value compared to incrementing a local value.
Noldorin
@Noldorin, I agree, but it's what the user asked for. I'll add some qualifications
JaredPar
@JaredPar: Yes, indeed, the asker did seem to want something like that. Anyway, it's a good answer now with the alternative (slightly nicer) and the qualifications added.
Noldorin
A: 

Duplicate of this question?

cottsak
A: 

This is probably the simplest way, if you're going to stick to a foreach loop. Nothing level, but I think it's the best way to go still.

int rowIndex = 0;
foreach (int a in numbers)
{
    rowIndex++; // You could of course inline this wherever rowIndex first
                // gets used, and then simply reference rowIndex (without
                // the increment) later.

    // ...
}

But once you start doing this, it's probably best just to use an ordinary for loop anyway (unless you can't because the collection only implements IEnumerable and not IList/ICollection of course).

Noldorin