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?
This guideline is from C# in Depth :
As long as you are okey in exposing this extension method on all instances of type IEnumerable, then you are good to go.
On a lighter note, I would rather call the extension method as
ToSelectListItem, rather thanToSelectList, to make it clear for the end user. Again this is my personal preference.