Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String[] to List<SelectList>

Tags:

c#

asp.net

Is there an easy way, without looping over all the items in an array manually, to convert to a SelectList from an array of strings for a drop down menu?

like image 279
Ellery Avatar asked Feb 24 '15 15:02

Ellery


1 Answers

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.

like image 93
D Stanley Avatar answered Sep 21 '22 15:09

D Stanley