Creating a select list from an array
17,106
Solution 1
Use overloaded Enumerable.Select method:
model.month = months
.Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()});
Solution 2
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()});
Solution 3
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
Author by
Jeff
Updated on June 25, 2022Comments
-
Jeff almost 2 years
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?