For each, we get RowIndex

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

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 to do this? Maybe using extension methods?

+1


a source to share


2 answers


Try to run

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

      

There is a select overload that skips the item index. This code will create a new anonymous type for each element that includes both an index and a value.



Here's an alternative way that makes the syntax a little 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
}

      

It doesn't add much by the definition of local and increments it manually. Is there a specific reason why you don't want to do this?

+4


a source


This is probably the easiest way if you are going to stick with a foreach loop. Nothing level, but I think this is the best way to still stay.

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 that, it's best to just use a regular for loop (anyway) if you can't, because collection only implements IEnumerable

, not IList

/ ICollection

).

0


a source







All Articles