Enumerator to SelectList Generic Method

 

So anyone reading this probably knows that when using a DropDownFor or any custom list type Html Helper, usually you will need to convert whatever IEnumerable you have at your disposal to a SelectList. There is no ToSelectList method like there is with List or Queryable. In most cases, that is probably a two or 3 line ordeal, nut what if you have an Enumeration that you need to turn into a SelectList. Not quite as straight forward. So I created a Generic method that we could use throughout or project and thought it might be useful to others, so I’m posting it here.

Lets assume we have an enumeration that looks like this:

public enum DaysofWeek
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 3
    Wednesday=4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
}

 

public static SelectList EnumToSelectList<T>()
       {
           var list = Enum.GetValues(typeof(T)).Cast<int>().Select(enu => new SelectListItem() { Text = Enum.GetName(typeof(T), enu), Value = enu.ToString() });
           return new SelectList(list, "Value", "Text");
       }

 

So lets discuss what’s going on here. The first thing we are doing is setting the method to public static and a return type of SelectList. Then after the method name, we are telling the method to accept a type before the declaration without any parameters. The reason we don’t really need any parameters is because when you declare an enumerator, that will imply a pointer to all the items associated with it. This will give us access to the items to cycle through them later on.

In the body of the method there is some interesting things going on. The GetValues requires a Type so it knows what enumeration we are dealing with. That is where the type being declared in the message body comes in. We then cast this to an int. Why you may say? Well because an enumeration always has to parts. One part is the Key (which is the name in used in the code  ie. Sunday, Monday, Tuesdaty etc…). The second part is the actual value (which is always an integer). After that, we use LINQ’s handy Select method to create an anonymous function that creates a SelectListItem for each enumerator and sets the Text to it’s name which is basically the key ands sets the value to the actual value. Then when all is done, we create a new SelectList, pass in the new list of Select Items, and tell the new SelectList what to use for the value, and what to use for the Text. In the case of a SelectListItem, it will always be the Text and Value fields.

Due to the use of Generics, you could actually use this for ANY enumeration. You also could change the method inside to have the LINQ Select method return you anything you would like it to be, just in this example, we are using SelectLists.

Finally, to use this method, using the above enumerator, you would do something like this.

var daysOfWeek = EnumToSelectList<DaysofWeek>();

daysofWeek would then have a SelectList with a list of SelectListItems filled with you days of the week name and values as you need for the DropdownFor.

 

 

I hope this will helped others.

Happy Coding 🙂

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, ASP.NET, C#, Classes, Generics, LINQ, LINQ To SQL, MVC and tagged , , , , , , , . Bookmark the permalink.

3 Responses to Enumerator to SelectList Generic Method

  1. Pingback: ASP.NET MVC – No parameterless constructor defined for this object | Object Reference Hell

  2. anti snoring says:

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment.
    Is there any way you can remove me from that service?

    Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s