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 ?
-
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?
Noldorin : 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.JaredPar : @Noldorin, I agree, but it's what the user asked for. I'll add some qualificationsNoldorin : @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. -
Duplicate of this question?
-
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 notIList
/ICollection
of course).
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.