Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert new item into an IEnumerable

I create a dropdownlist from Enum.

public enum Level
{
    Beginner = 1,
    Intermediate = 2,
    Expert = 3
}

here's my extension.

    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
    {

        IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

        var result = from TEnum e in values
                     select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };

        var tempValue = new { ID = 0, Name = "-- Select --" };


        return new SelectList(result, "Id", "Name", enumObj);
    }

the problem I have is to insert antoher item into IEnumerable. I just could not figure out how to do it. Can someone please modify my code to insert "--select--" to the top.

like image 905
qinking126 Avatar asked Aug 09 '11 15:08

qinking126


1 Answers

You can't modify a IEnumerable<T> object, it only provides an interface to enumerate elements. But you could use .ToList() to convert the IEnumerable<T> to a List<T>.

I'm not sure if this is what you want:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{

    IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

    var result = from TEnum e in values
                 select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };

    var tempValue = new { ID = 0, Name = "-- Select --" };

    var list = result.ToList(); // Create mutable list

    list.Insert(0, tempValue); // Add at beginning of list

    return new SelectList(list, "Id", "Name", enumObj); 
}
like image 145
Fox32 Avatar answered Nov 15 '22 14:11

Fox32