In the Type Safe SelectList Factory post I showed one way to improve the SelectList constructor. Recently I wrote another one, when I needed a SelectList that has the selected item’s index as the value. I used this together with jQuery to get details about the selected item from a separately supplied json array.
public static SelectList ToSelectList<TSource, TText>( this IEnumerable<TSource> source, Func<TSource, TText> dataTextField) { var indexedSource = source.Select((s, i) => new { Index = i, Text = dataTextField(s) }); return ToSelectList(indexedSource, s => s.Index, s => s.Text); } |
To create the indexed source I’m using an overload of Select() that feeds both an object and its index to the lambda. Based on it, I create a new sequence containing just the text field and an index. Finally I feed it into the ToSelectListmethod I wrote in the Type Safe SelectList Factory post.