I saw several examples of using "T" to make the method reusable for general collections of different classes, but I never got into it or understood the patterns.
I wonder if it is possible to put 2 methods below into one and what could mean that it will (in terms of performance).
Is 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;
}
Decision
The solution I used:
Using
var departmentItems = departments.ToSelectList(d => d.Code + " - " + d.Description, d => d.Id.ToString(), " - ");
var functionItems = customerFunctions.ToSelectList(f => f.Description, f => f.Id.ToString(), " - ");
from
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;
}
}
source
share