关于.net:所有枚举项到字符串(C#)

All Enum items to string (C#)

如何将所有元素从枚举转换为字符串?

假设我有:

1
2
3
4
5
6
public enum LogicOperands {
        None,
        Or,
        And,
        Custom
}

我想归档的是:

1
2
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"


1
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));

你必须这样做:

1
2
3
4
5
6
7
var sbItems = new StringBuilder()
foreach (var item in Enum.GetNames(typeof(LogicOperands)))
{
    if(sbItems.Length>0)
        sbItems.Append(',');
    sbItems.Append(item);
}

或在LINQ中:

1
var list = Enum.GetNames(typeof(LogicOperands)).Aggregate((x,y) => x +"," + y);


1
2
3
string LogicOperandsStr
     = Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=>
                                                       current +"," + next);

虽然@moose的答案是最好的,但是我建议您缓存这个值,因为您可能经常使用它,但是在执行期间它是100%不可能改变的——除非您正在修改和重新编译枚举。:)

像这样:

1
2
3
4
5
public static class LogicOperandsHelper
{
  public static readonly string OperandList =
    string.Join(",", Enum.GetNames(typeof(LogicOperands)));
}

将枚举转换为可以交互的对象的简单通用方法:

1
2
3
4
public static Dictionary<int, string> ToList<T>() where T : struct
{
   return ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(item => Convert.ToInt32(item), item => item.ToString());
}

然后:

1
var enums = EnumHelper.ToList<MyEnum>();

1
2
3
4
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
    str = str +"," + value;
}