Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way I can determine which row I am on in a foreach loop?

Tags:

c#

.net

foreach

I have this code:

foreach (var row in App.cardSetWithWordCounts)
{
   details.Children.Add(new SeparatorTemplate());
   // do some tasks for every row 
   // in this part of the loop ...
}

I would like to not do the adding of a SeparatorTemplate BUT I would like to do the other tasks on the first run of the foreach. Does anyone have a suggestion on how I can do this?

I want to execute the rest of the code in the foreach but not the line adding the template on the first time around.

like image 683
Alan2 Avatar asked Oct 03 '18 10:10

Alan2


1 Answers

If you want to skip the first row, you can use Skip:

foreach (var row in App.cardSetWithWordCounts.Skip(1))

If you want to know the exact row number, use the Select overload:

foreach (var x in App.cardSetWithWordCounts.Select((r, i) => new { Row = r, Index = i })
{
    // use x.Row and x.Index
}
like image 149
Patrick Hofman Avatar answered Sep 28 '22 07:09

Patrick Hofman