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?
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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With