1

我有以下枚举:

 public enum Brands
    {
        HP = 1,
        IBM = 2,
        Lenovo = 3
    }

从中我想制作一个格式的字典:

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

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

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

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;
        }

谢谢!

4

2 回答 2

7

您可以使用Enumerable.ToDictionary()创建您的字典。

不幸的是,编译器不会让我们将 TEnum 转换为 int,但是因为您已经断言该值是 Enum,所以我们可以安全地将其转换为对象,然后再转换为 int。

var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString());
于 2013-10-11T10:32:50.847 回答
2

//使用这段代码:

 Dictionary<string, string> dict = Enum.GetValues(typeof(Brands)).Cast<int>().ToDictionary(ee => ee.ToString(), ee => Enum.GetName(typeof(Brands), ee));
于 2013-10-11T10:33:15.573 回答