Convert String[] to List<SelectList>
I'm assuming you need either a SelectList
or a List<SelectListTiem>
, not a List<SelectList>
. SelectList
has a constructor that takes a collection:
string[] strings = new [] { .. strings .. };
SelectList sl = new SelectList(strings);
or you can project to a List<SelectListItem>
:
string[] strings = new [] { .. strings .. };
var sl = strings.Select(s => new SelectListItem {Value = s})
.ToList();
Note that SelectList
implements IEnumerable<SelectListItem>
, so if you have a model property of type IEnumerable<SelectListItem>
you can create a SelectList
and assign it to that property rather than projecting to a List<SelectListItem>
. It's functionally the same but the code will be a little cleaner.
This is all assuming we're talking about MVC, not Web Forms
Second to D Stanley's answer, another solution:
string[] strings = new [] { ... strings ... };
var selectListItems = strings.Select(x => new SelectListItem() { Text = x, Value = x, Selected = x == "item 1" });
A list of SelectListItem
can also be used to populate an MVC drop down list.
With this method, you can also set other properties on a SelectListItem
such as, display value.
We can't call Select
on a IQueryable
using the SelectListItem
constructor because LINQ will try and convert that to SQL. Which unless there is a provider for it, is impossible, and also not what we want to achieve.
In order to always assure we can enumerate like I have shown above, we need to force EF or other ORMs to get all our data back. We can do this by calling ToList()
BEFORE we enumerate with Select
:
var selectListItems = strings.ToList().Select(x => new SelectListItem() { Text = x, Value = x, Selected = x == "item 1" });
As @BCdotWEB has pointed out:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
Is the constructor that this list will inevitably get put into. If I can remember correctly, the razor view should look like this:
@Html.DropDownListFor(x => x.SelectedString, new SelectList(x.Strings, "Value", "Text"))
Where x.SelectedString
is where you want the chosen value from the drop down to be put. x.Strings
is that selectListItems
we created in the Controller
/Service