如何从枚举中提取数据并使其成为IEnumerable?

时间:2012-09-15 09:56:49

标签: c#

我有以下枚举:

public enum ReferenceKey {
    MenuType             = 1,
    ReferenceStatus      = 2,
    ContentType          = 3
}

有没有办法可以将此数据列为IEnumerable 两个领域。数字的第一个字段和第二个字段 在第一个和第二个单词之间有空格的字符串,如:

1  "Menu Type"
2  "Reference Status"
3  "Content Type"

4 个答案:

答案 0 :(得分:4)

  

有没有办法可以将这些数据列为具有两个字段的IEnumerable。数字的第一个字段和第二个字符串,第一个和第二个字之间有空格

为什么不

解决方案2:您想要的数组

IEnumerable<ReferenceKey> v = 
                       Enum.GetValues(typeof(ReferenceKey)).Cast<ReferenceKey>();

string[] result = 
                  v.Select(x => (int)x + " \"" + x.ToString() + " \"").ToArray();

看到它正常工作

enter image description here


解决方案2:Dictionary<int, string>

string[] str = Enum.GetNames(typeof(ReferenceKey));

Dictionary<int, string> lst = new Dictionary<int, string>(); 

for (int i = 0; i < str.Length; i++)
    lst.Add((int)(ReferenceKey)Enum.Parse(typeof(ReferenceKey), str[i]), str[i]);

看到它正常工作

enter image description here


解决方案3:创建Dictionary<int, string>

的另一种方法
Array v = Enum.GetValues(typeof(ReferenceKey));

Dictionary<int, string> lst = v.Cast<ReferenceKey>()
                               .ToDictionary(x => (int)x, 
                                             x => x.ToString());

为此

添加System.Linq命名空间

看到它正常工作

enter image description here

答案 1 :(得分:4)

Dictionary与静态GetNamesGetValues方法结合使用。

 var names = ReferenceKey.GetNames(typeof(ReferenceKey));
 var values = ReferenceKey.GetValues(typeof(ReferenceKey)).Cast<int>().ToArray();

 var dict = new Dictionary<int, string>();
 for (int i = 0; i < names.Length; i++)
 {
     string name = names[i];
     int numChars = name.Length;
     for (int c = 1; c < numChars; c++)
     {
         if (char.IsUpper(name[c]))
         {
             name = name.Insert(c, " ");
             numChars++;
             c++;
         }
     }
     dict[values[i]] = name;
 }

GetValues
GetNames

要获取您指定的格式,您可以执行以下操作:

string[] formatted = dict.Select(s => String.Format("{0} \"{1}\"", s.Key, s.Value)).ToArray();

答案 2 :(得分:3)

如果你只想把它作为一个简单的可枚举,那就这样做:

var names = Enum.GetNames(typeof(ReferenceKey));
var values = Enum.GetValues(typeof(ReferenceKey)).Cast<int>();
var pairs = names.Zip(values, (Name, Value) => new { Name, Value });

你得到这个结果:

Enumerable Pairs

如果您希望将其作为字典,请执行以下操作:

var dict = pairs.ToDictionary(x => x.Name, x => x.Value);

你得到这个结果:

Dictionary Pairs

如果您想在每个单词之间添加空格,可以将.Select(n => Regex.Replace(n, "([A-Z])", " $1").Trim());添加到names变量定义。

使用此间距代码,您现在可以获得以下结果:

Spacing Results

答案 3 :(得分:2)

每种枚举类型的更通用的方法:

    static IEnumerable<string> EnumToEnumerable(Type x)
    {
        if (x.IsEnum)
        {
            var names = Enum.GetValues(x);

            for (int i = 0; i < names.Length; i++)
            {
                yield return string.Format("{0} {1}", (int)names.GetValue(i), names.GetValue(i));
            }
        }
    }

调用
EnumToEnumerable(typeof(ReferenceKey));