Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Generic Enum to List<T> converter (C#)

One for the utility library...

Here's a small function I've found to be quite useful recently. It takes an enum type and returns a generic list populated with each enum item.

        public static List<T> EnumToList<T>()
        {
            Type enumType = typeof (T);

            // Can't use type constraints on value types, so have to do check like this
            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T must be of type System.Enum");
            
            Array enumValArray = Enum.GetValues(enumType);

            List<T> enumValList = new List<T>(enumValArray.Length);

            foreach (int val in enumValArray) {
                enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
            }

            return enumValList;
        }

Here's one of the ways that I've used it:

List<DayOfWeek> weekdays =
    EnumHelper.EnumToList<DayOfWeek>().FindAll(
        delegate (DayOfWeek x)
        {
            return x != DayOfWeek.Sunday && x != DayOfWeek.Saturday;
        });

Posted 10-10-2006 11:40 AM by Joe Niland
Filed under:

[Advertisement]

Comments

Michal Grzegorzewski wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 9:36 AM

pretty cool! :)

Michal Grzegorzewski wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 9:53 AM

what about:

public static List<T> EnumToList<T>()

{

 Type enumType = typeof(T);

 // Can't use type constraints on value types, so have to do check like this

 if (enumType.BaseType != typeof(Enum))

  throw new ArgumentException("T must be of type System.Enum");

 return new List<T>(Enum.GetValues(enumType) as IEnumerable<T>);

}

isn't this a little bit faster?

Rob Eisenberg wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 9:54 AM

Cool.  I can think of quite few scenarios where this will be very useful.  Thanks for the source.

Joe Niland wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 10:19 AM

mgrzeg,

Yes - you've found the missing link! I wasn't aware List<T> has that constructor.

Thanks for that - I've updated my library!

Cheers

Joe Niland wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 10:45 AM

I just did rough performance test and the difference appears to be negligible. So it's definitely better to use mgrzeg's version as it's less code! Thanks again..

Michal Grzegorzewski wrote re: Generic Enum to List<T> converter (C#)
on 10-10-2006 8:47 PM

Joe,

I've prepared my own performance tests and found out, that mine version is about 5 times faster and produces 8 times less garbage collections than yours on test with an enum with 100k elements (rather strange, isn't it? ;)) For timings I used the OperationTimer class from Jeff Richter's 'CLR via C#' - chapter about Generics.

But who uses such a big enum that should be aware of the size? Definitely in every day use it doesn't matter, what version is being used - mine or yours.

Joe Niland wrote re: Generic Enum to List<T> converter (C#)
on 10-11-2006 5:09 AM

Hi,

Yes i did a rather lame rough test using DateTime.Now just to see if the difference was drastic. Was planning to do the high-res timer test but now you've done it we can see the results!

I would like to look at the IL generated to see exactly how they differ and hence the reason for the speed increase. The overhead in creating the intermediate array would be one thing.

You're right - it would be very rare to have such a huge list of enums! Still it is always good to choose the higher performing version if it poses no issues, since then you avoid nasty surprises later on as your app scales in size.

Thanks for the analysis. Very interesting..

Peter Mescalchin wrote re: Generic Enum to List<T> converter (C#)
on 10-12-2006 11:02 AM

I'm impressed with the quality of posts coming out of this blog. Keep it up guys - good to see another great .NET blog!

Laboremus wrote re: Generic Enum to List<T> converter (C#)
on 11-04-2006 7:59 PM

Hi Joe. It still not completely generic - what if enum base type not int? How we can properly cast values to receive numbers?

Unfortunatelly Enum.GetNames and Enum.GetValues are giving exactly the same output if you don't cast it to the type.

Is there solution for this problem?

Useful C#.Net Enum List Method « Welcome to Matt’s Blog, Please Keep to the Posted Speed Limit wrote Useful C#.Net Enum List Method &laquo; Welcome to Matt&#8217;s Blog, Please Keep to the Posted Speed Limit
on 08-15-2007 5:49 PM

Pingback from  Useful C#.Net Enum List Method &laquo; Welcome to Matt&#8217;s Blog, Please Keep to the Posted Speed Limit

http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx wrote http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx
on 03-21-2008 2:23 AM
Extending the DropDownList to Support Enums « using … wrote Extending the DropDownList to Support Enums &laquo; using &#8230;
on 10-10-2008 7:05 AM

Pingback from  Extending the DropDownList to Support Enums &laquo; using &#8230;

BabbaBlog wrote Enum to List
on 09-30-2009 12:49 PM

Enum to List

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)