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

后端 未结 3 2005
遇见更好的自我
遇见更好的自我 2021-01-18 09:33

Given an enum like this:

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

public enum House {
    OneFloor    = 1,
    TwoF         


        
3条回答
  •  独厮守ぢ
    2021-01-18 10:05

    Use Jon Skeet's unconstrained melody.

    using UnconstrainedMelody;
    

    You can put your enum values into a Dictionary and then enumerate over them:

    var valuesAsDictionary = Enums.GetValues()
                                  .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())
    {
        Console.WriteLine("{0}: {1}", (int)value, value);
    }
    

提交回复
热议问题