关于.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"

  • 检查这个答案也很有用:stackoverflow.com/a/12022617/1830909


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);

  • 我在想类似的LINQ版本,你打败了我。+ 1
  • 请不要这样滥用StringBuilder!
  • Randolpho StringBuilder代码有什么问题?什么虐待?
  • 事实上,我觉得没问题。使用string.join更整洁,但我看不到任何"滥用"。
  • 除非枚举中有几十个项,否则最好使用字符串串联。
  • 进一步阅读:stackoverflow.com/questions/529999/when to use string builde‌&8203;r/…
  • 等待。。。你没有给乔恩写正确的答案吗?这是一个微不足道的循环。StringBuilder太过分了。


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;
}

  • 你错过了逗号
  • 你必须删去最后一个逗号