Konrad Viltersten
Konrad Viltersten

Reputation: 39278

How to count without a counter in a select?

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++ });

Upvotes: 5

Views: 110

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

Use this overload of Select

IEnumerable<Typo> result = originals.Select((original, counter)
  => new Thingy { Name = "Hazaa" + (counter + 1) });

Upvotes: 12

Related Questions