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

后端 未结 3 1966
遇见更好的自我
遇见更好的自我 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 09:50

    This function might help you:

    public static IEnumerable> GetValues() where T : struct
    {
            var t = typeof(T);
            if(!t.IsEnum)
                throw new ArgumentException("Not an enum type");
    
            return Enum.GetValues(t).Cast().Select (x => 
                   new KeyValuePair(
                       (int)Enum.ToObject(t, x), 
                        x.ToString()));
    }
    

    Usage:

    var values = GetValues();
    

提交回复
热议问题