IEnumerable Extension
.net, c#, extension-methods, ienumerable
Solution
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 `TKey` type parameter. And there is no need to create a list in the extension method. An iterator block using `yield return` is preferable and how similar extension methods in LINQ are built.
public static IEnumerable<SelectListItem> ToSelectItemList<TSource>(
this IEnumerable<TSource> enumerable,
Func<TSource, string> text,
Func<TSource, string> value)
{
foreach (TSource model in enumerable)
yield return new SelectListItem { Text = text(model), Value = value(model) };
}
You can use it like this (you need to supply the two lambdas):
var selectedItems = items.ToSelecListItem(x => ..., x => ...);
However, you could just as well use `Enumerable.Select`:
var selectedItems = items.Select(x => new SelectListItem { Text = ..., Value = ... });
Problem
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>` ?