I use an extension method:
usage
var departmentItems = departments.ToSelectList(d => d.Code +
" - " + d.Description,
d => d.Id.ToString(),
" - ");
var functionItems = customerFunctions.ToSelectList(f => f.Description,
f => f.Id.ToString(),
" - ");
with
public static class MCVExtentions
{
public static List<SelectListItem> ToSelectList<T>(
this IEnumerable<T> enumerable,
Func<T, string> text,
Func<T, string> value,
string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem()
{
Text = text(f),
Value = value(f)
}).ToList();
items.Insert(0, new SelectListItem()
{
Text = defaultOption,
Value = "-1"
});
return items;
}
}