从枚举值创建字典

Mdb*_*Mdb 1 c# enums

我有以下枚举:

 public enum Brands
    {
        HP = 1,
        IBM = 2,
        Lenovo = 3
    }
Run Code Online (Sandbox Code Playgroud)

从中我想以格式制作字典:

// key = name + "_" + id
// value = name

var brands = new Dictionary<string, string>();
brands[HP_1] = "HP",
brands[IBM_2] = "IBM",
brands[Lenovo_3] = "Lenovo"
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经这样做了,但是从这个方法创建字典有困难:

public static IDictionary<string, string> GetValueNameDict<TEnum>()
        where TEnum : struct, IConvertible, IComparable, IFormattable
        {
            if (!typeof(TEnum).IsEnum)
                throw new ArgumentException("TEnum must be an Enumeration type");

            var res = from e in Enum.GetValues(typeof (TEnum)).Cast<TEnum>()
                      select // couldn't do this

            return res;
        }
Run Code Online (Sandbox Code Playgroud)

谢谢!

drc*_*rch 6

您可以使用Enumerable.ToDictionary()来创建Dictionary.

不幸的是,编译器不会让我们将一个TEnum转换为int,但是因为你已经声明该值是一个Enum,我们可以安全地将它转换为一个对象然后一个int.

var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString());
Run Code Online (Sandbox Code Playgroud)