Sad*_*ami 2 c# asp.net foreach enums
我有一个枚举
public enum citys
{
a=1,
b=1,
c=1,
d=2,
e=2,
f=2,
};
Run Code Online (Sandbox Code Playgroud)
我希望Name以价值为基础返回.例如,在foreach return Enum.GetNames那里Value =1
result --> a,b,c
foreach return Enum.GetNames that Value =2
result --> d,e,f
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
那么你可以使用Enum.GetNames结合Enum.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));
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用反射获取字段:
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);
}
Run Code Online (Sandbox Code Playgroud)
使用枚举是否是一个很好的设计,你想要实现的目标还不是很清楚 - 这里真正的目标是什么?也许您应该使用查找代替?