I want to make an IEnumerable<TSource> extension that can convert itself to a IEnumerable<SelectListItem>. So far I have been trying to do it this way:
public static
IEnumerable<SelectListItem> ToSelectItemList<TSource, TKey>(this
IEnumerable<TSource> enumerable, Func<TSource, TKey> text,
Func<TSource, TKey> value)
{
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (TSource model in enumerable)
selectList.Add(new SelectListItem() { Text = ?, Value = ?});
return selectList;
}
Is this the right way to go about doing it? If so how do I draw the values from the appropriate values from the Func<TSource, TKey> ?
You just need to use the two functions you supply as parameters to extract the text and the value. Assuming both text and value are strings you don’t need the
TKeytype parameter. And there is no need to create a list in the extension method. An iterator block usingyield returnis preferable and how similar extension methods in LINQ are built.You can use it like this (you need to supply the two lambdas):
However, you could just as well use
Enumerable.Select: