Linq : Converting a List<> to a List<SelectListItem>
Just like when I was learning regular expression, I find that I’m using Linq to do more and more with my data objects the more I use it.
Also with regular expression I’m wary of using it because it’s still not in the “everyday developer’s” skill set and if said developer ever has to debug my work, they might find it a steep learning curve.
This example however I think this code for converting a List<> to a List<SelectListItem> is pretty neat and self explanatory:
List<SelectListItem> SelectListItemList =
(
from rec in myReadList
select new SelectListItem
{
Text = rec.Value,
Value = rec.Key
}
).ToList();
However, for those who DO want an explanation, this is what is happening:
- each item of a List<> named myReadList is read one-at-a-time into a variable called “rec”
- for each “rec” item a new “SelectListItem” object is made and the values rec.Value and rec.Key are read into the SelectListItem’s .Text and .Value properties
- Inside the brackets this will be returned as IEnumerable<SelectListItem> however I want it as a List<SelectListItem> so I call .ToList() afterwards.
For those who find the example above too long, here is the short-hand version. (It’s just one line, but broken so it wraps well)
List<SelectListItem> SelectListItemList =
myReadList.Select(
rec => new SelectListItem
{ Text = rec.Value, Value = rec.Key }).ToList();
UPDATE: For those wishing to set a default or selected item can find a solution (as chosen) at StackOverflow.