Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count without a counter in a select?

Tags:

c#

foreach

Sometimes, during development phase, I need to see if e.g. a name is changed for each element created or just wish to differentiate between different instances' names in an array. That behavior is strictly for development-stage and only to be applied during a short period of time (hence no need to long term solution - Q&D is just fine).

Usually, I introduce a counter in the following way but it just stroke me that there might be a better way. Basically, I wish to emulate behavior of the counter variable of for without actually introducing it (staying at foreach).

int counter = 1;
IEnumerable<Typo> result = originals.Select(original 
  => new Thingy { Name = "Hazaa" + counter++ });
like image 527
Konrad Viltersten Avatar asked Jul 16 '15 16:07

Konrad Viltersten


1 Answers

Use this overload of Select

IEnumerable<Typo> result = originals.Select((original, counter)
  => new Thingy { Name = "Hazaa" + (counter + 1) });
like image 180
Matt Burland Avatar answered Oct 29 '22 09:10

Matt Burland