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.
publicstatic 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);}
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.
You're currently writing a reply to an existing comment, so the comment form is busy elsewhere. To make a new
comment (that isn't a reply to an existing ocmment), you have to cancel that reply.