views:

584

answers:

3

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?

+1  A: 

How about

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

(I only tried the lambda expression with its capture of index. I don't know about the other classes.)

Hosam Aly
I like your style!However I can't seem to even assign something to "x.Name" ForEach(x => x.Name = "test") returns an error. Perhaps you can't re-assign in a forEach()? :S
GONeale
You can do an assignment (as long as x is a class), but I don't know the structure of ViewData.Model.Formats, so I'm sorry I can't help you here. Also check Neil's answer. It's better in my opinion.
Hosam Aly
Hosam, yes 'x' is a class, but the assignment was stating 'cannot convert void to IEnumerable' or something and disallowed it.
GONeale
+2  A: 

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.

Neil Williams
Thanks for the information. I didn't know about it.
Hosam Aly
Great Neil, can you update your example to include 'ID' in the select?
GONeale
A: 

With great 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 })

Anon methods rock!

GONeale