Indexed SelectList Factory

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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.