2013-06-19 93 views
2

我有一个枚举返回枚举名称基值

public enum citys 
{ 
     a=1, 
     b=1, 
     c=1, 
     d=2, 
     e=2, 
     f=2, 
}; 

而且我要在值。例如返回Name基地,foreach return Enum.GetNamesValue =1

result --> a,b,c 
foreach return Enum.GetNames that Value =2 
result --> d,e,f 

感谢您的帮助。

回答

5

那么你可以结合使用Enum.GetNamesEnum.Parse - 这不是我最好喜欢做的,但它的工作原理:

using System; 
using System.Collections.Generic; 
using System.Linq; 

public enum City 
{ 
     a=1, 
     b=1, 
     c=1, 
     d=2, 
     e=2, 
     f=2, 
} 

class Test 
{ 
    static void Main() 
    { 
     // Or GetNames((City) 2) 
     foreach (var name in GetNames(City.a)) 
     { 
      Console.WriteLine(name); 
     } 
    } 

    static IEnumerable<string> GetNames<T>(T value) where T : struct 
    { 
     return Enum.GetNames(typeof(T)) 
        .Where(name => Enum.Parse(typeof(T), name).Equals(value)); 
    } 
} 

或者你可以得到等领域的反映:

static IEnumerable<string> GetNames<T>(T value) where T : struct 
{ 
    return typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static) 
        .Where(f => f.GetValue(null).Equals(value)) 
        .Select(f => f.Name); 
} 

使用枚举是否是一个很好的设计来达到你想达到的目的并不是很清楚 - 虽然这里真正的目标是什么?也许你应该使用查找呢?

+0

非常感谢我的问题从你的code.thanks解决 –