1

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 ?

Melursus
  • 9,436
  • 18
  • 66
  • 101
  • possible duplicate of [(C#) Get index of current foreach iteration](http://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration) – Brad Mace Aug 24 '11 at 01:28
  • Duplicate of [this question](http://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration)? – Matt Kocaj May 09 '09 at 19:10

2 Answers2

4

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?

tvanfosson
  • 490,224
  • 93
  • 683
  • 780
JaredPar
  • 673,544
  • 139
  • 1,186
  • 1,421
  • 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 May 09 '09 at 19:14
  • @Noldorin, I agree, but it's what the user asked for. I'll add some qualifications – JaredPar May 09 '09 at 19:28
  • @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 May 09 '09 at 20:08
0

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
  • 134,265
  • 53
  • 250
  • 293