Hello,
I've seen some samples of using 'T' to make a method reuseable for generic collections of different classes, but I've never really gotten into it or understood the samples.
I wonder if it would be possible to put the 2 methods below into one and what the downsides of doing this would be (performance-wise).
Anyone?
[NonAction]
public List<SelectListItem> ToSelectList(IEnumerable<Department> departments, string defaultOption)
{
var items = departments.Select(d => new SelectListItem() { Text = d.Code + " - " + d.Description, Value = d.Id.ToString() }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
[NonAction]
public List<SelectListItem> ToSelectList(IEnumerable<Function> functions, string defaultOption)
{
var items = functions.Select(f => new SelectListItem() { Text = f.Description, Value = f.Id.ToString() }).ToList();
items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
return items;
}
SOLUTION
The solution that I used:
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;
}
}