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 Reply

    Your name as it will be displayed on the posted comment.
    Your e-mail address will not be published. It is only used if I want to get in touch during comment moderation.
    Your name will be a link to this address.
Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts



Powered by WordPress with the Passion for Coding theme.