Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Generics to create a way of making an IEnumerable from an enum?

Tags:

c#

Given an enum like this:

public enum City {
    London    = 1,
    Liverpool  = 20,
    Leeds       = 25
}

public enum House {
    OneFloor    = 1,
    TwoFloors = 2
}

I am using the following code to give me an IEnumerable:

City[] values = (City[])Enum.GetValues(typeof(City)); 
var valuesWithNames = from value in values                       
   select new { value = (int)value, name = value.ToString() }; 

The code works very good however I have to do this for quite a lot of enums. Is there a way I could create a generic way of doing this?

like image 694
Samantha J T Star Avatar asked Sep 16 '12 14:09

Samantha J T Star


1 Answers

Use Jon Skeet's unconstrained melody.

using UnconstrainedMelody;

You can put your enum values into a Dictionary<int, string> and then enumerate over them:

var valuesAsDictionary = Enums.GetValues<City>()
                              .ToDictionary(key => (int)key, value => value.ToString());

But you probably don't even need to do that. Why not just enumerate over the values directly:

foreach (var value in Enums.GetValues<City>())
{
    Console.WriteLine("{0}: {1}", (int)value, value);
}
like image 109
Adam Avatar answered Oct 13 '22 11:10

Adam