从枚举填充字典

时间:2013-03-10 16:09:41

标签: linq dictionary enums

我有以下枚举:

public enum LifeCycle
{
    Pending = 0,
    Approved = 1,
    Rejected = 2,
}

我想创建

Dictionary<int, string> LifeCycleDict;  

来自enum及其toString

有没有办法用linq做呢?
(等同于java的enum.values) 感谢。

1 个答案:

答案 0 :(得分:6)

Dictionary<int, string> LifeCycleDict = Enum.GetNames(typeof(LifeCycle))
    .ToDictionary(Key => (int)Enum.Parse(typeof(LifeCycle), Key), value => value);

OR

Dictionary<int, string> LifeCycleDict = Enum.GetValues(typeof(LifeCycle)).Cast<int>()
    .ToDictionary(Key => Key, value => ((LifeCycle)value).ToString());

OR

Dictionary<int, string> LifeCycleDict = Enum.GetValues(typeof(LifeCycle)).Cast<LifeCycle>()
    .ToDictionary(t => (int)t, t => t.ToString());