score:6

Accepted answer

there are two options:

if you can implement an interface on the entity

public interface iselectable
{
    string name { get; }
    int id { get; }
}
public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection)
    where t: iselectable
{
    return collection.select(m => new selectlistitem
    {
        text = m.name,
        value = m.id.tostring()
    }).tolist();
}

using delegates

public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection, func<t, string> namegetter, func<t, int> idgetter)
{
    return collection.select(m => new selectlistitem
    {
        text = namegetter(m),
        value = idgetter(m).tostring()
    }).tolist();
}

usage :

m.employmentstatus.toselectitemlist(e => e.name, e => e.id);

the second option is more verbose to use, but you get a ton more flexibility, since you don't have to clutter your data model with useless interface implementation, and you are free to use any property names for name or id

score:3

dropdownlistfor requires a ienumerable<selectlistitem> selectlist as a collection

there's already a class for that, namely selectlist:

var selectlistitems = new selectlist(items, "id", "name");

no need for new extension methods whatsoever. i thought selectlist() also has an overload with expressions for the key/value members instead of strings, but i may have found that somewhere else.

see also asp.net mvc dropdown list from selectlist.

score:8

you can define an interface for all entities that you are going to use for dropdownlists like

public interface idropdownitem
{
   int id {get; set;}
   string name {get; set;}
}

then

public static list<selectlistitem> toselectitemlist<t>(ienumerable<t> collection) 
   where t : idropdownitem
{
    return collection.select(m => new selectlistitem
    {
        text = m.name,
        value = m.id.tostring()
    }).tolist();
}

it would be better to make toselectitemlist as extension method:

public static class enumerableextensions
{
    public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection)
        where t : program
    {
        return collection.select(m => new selectlistitem
        {
            text = m.name,
            value = m.id.tostring()
        }).tolist();
    }
}

Related Query

More Query from same tag