2

Possible Duplicate:
how to find the index particular items in the list using linq?

I am trying to create a IEnumerable<SelectListItem> from an array of strings.

string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

model.month = months
        .Select(r => new SelectListItem{Text = r, Value = ???});

Is there a way to access their index within this query?

Community
  • 1
  • 1
Jeff
  • 2,283
  • 9
  • 32
  • 50

3 Answers3

13

Use overloaded Enumerable.Select method:

model.month = months
    .Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()});
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    Thank you for the reference. As a note, `Value` must be of type string so `Value = index.ToString()` would be correct – Jeff Jan 02 '13 at 21:43
5

Try with Enumerable.Select.

Projects each element of a sequence into a new form by incorporating the element's index.

model.month = months
        .Select((r, i) => new SelectListItem{Text = r, Value = i.ToString()});
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2

Jeff this should work for you based on the example on the link that lila G posted

string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
var query = months.Select((r, index) => new  { Text = r, Value = index });

Screen shot of what it looks like in the Debugger

enter image description here

MethodMan
  • 18,625
  • 6
  • 34
  • 52