I'm looking to make certain functions as generic as possible.
In my MVC applications I have to convert a number of complex IEnumerable objects to SelectLists for dropdown display etc.
At first I created a static List class with conversion methods for each complex object. This amounted to a lot of code. I next started using linq statements to do the conversion:
var list = (from o in SessionTypes select new SelectListItem { Value = o.ID.ToString(), Text = o.Title }).ToList();
but again, this still was a lot of code when taken over many such conversions.
I finally settled something similar to:
public IEnumerable<SelectListItem> ToSelectList<T>(IEnumerable<T> enumerable, Func<T, string> value, Func<T, string> text)
{
return enumerable.Select(f => new SelectListItem()
{
Value = value(f),
Text = text(f),
});
}
and to make it easier to use, I made it an extension method:
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> value, Func<T, string> text)
{
return enumerable.Select(f => new SelectListItem()
{
Value = value(f),
Text = text(f),
});
}
So now, all I have to do is:
var list = SessionTypes.ToSelectList(o => o.ID.ToString(), o => o.Title) as List<SelectListItem>;
I have similar methods such as .ToDictionary too.
Is this overusing Extension methods? I worry that I'm hiding too much code away in extension methods which might be distorting my models, would it be better to use linq conversions for transparency?
You can bind IDictionary<,> to the DropDownList DataSource directly, in WebForms you need to specify mappings like DataValueField="Key" and DataTextField="Value". Considering that why not just use LINQ ToDictionary() method?
dropDownList.DataValueField = "Key";
dropDownList.DataTextField = "Value";
dropDownList.DataSource =
SessionTypes.ToDictionary(k => k.ID.ToString(),
v => v.Title);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With