Lambda ForEach () Index position

This is somewhat asp.net MVC linked just for example, but I was hoping to achieve something like this:

new SelectList(ViewData.Model.Formats.ToList().ForEach(x => index + " - " + x.Name), "ID", "Name");

      

Basically trying to be smart and return "index" as a number 1 - n, where n is the number of items in the list ViewData.Model.Formats

, so my picklist is prefixed in every entry. Any easy way to do this, or am I looking at creating a new list with this lambda trick adding and breaking away?

+1


source to share


3 answers


With a lot of help from Neil and Hosam, I got this working with the following:

new SelectList(ViewData.Model.MessageTypeFieldFormats.Select((x, i) => new { ID = x.ID, Name = (i + 1) + " - " + x.Name })

      



Anonymous rock techniques!

-1


source


You can take advantage of the fact that LINQ Select can give you the index of each element:

new SelectList(ViewData.Model.Formats.Select((x, i) => (i + 1) + " - " + x.Name, "ID", "Name");

      



Note that this does not mean database access, only standard LINQ to Objects.

+4


source


What about

int index = 0;
new SelectList(ViewData.Model.Formats.ForEach(x => ++index + " - " + x.Name), "ID", "Name");

      

(I've only tried lambda expression with capturing it index

. I don't know about other classes.)

+1


source







All Articles