Asp – Lambda ForEach() Index Position

asp.net-mvclambda

This is somewhat asp.net MVC related only for example purposes 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 select list has a # prefixed on each entry. Any simple way to do this, or am I looking at making a new list with that append and ditching the lambda trick?

Best Solution

You could use the fact that LINQ's 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 doesn't mean any database access, just standard LINQ to Objects.