如何将所有元素从枚举转换为字符串?
假设我有:
public enum LogicOperands {
None,
Or,
And,
Custom
}
我要存档的内容如下:
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"
答案 0 :(得分:64)
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));
答案 1 :(得分:12)
你必须做这样的事情:
var sbItems = new StringBuilder()
foreach (var item in Enum.GetNames(typeof(LogicOperands)))
{
if(sbItems.Length>0)
sbItems.Append(',');
sbItems.Append(item);
}
或者在Linq:
var list = Enum.GetNames(typeof(LogicOperands)).Aggregate((x,y) => x + "," + y);
答案 2 :(得分:2)
string LogicOperandsStr
= Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=>
current + "," + next);
答案 3 :(得分:1)
尽管@ Moose的答案是最好的,但我建议你缓存这个值,因为你可能经常使用它,但是在执行期间它不可能100%改变 - 除非你正在修改和重新编译枚举。 :)
像这样:
public static class LogicOperandsHelper
{
public static readonly string OperandList =
string.Join(",", Enum.GetNames(typeof(LogicOperands)));
}
答案 4 :(得分:0)
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
str = str + "," + value;
}
答案 5 :(得分:0)
将枚举转换为可以互动的内容的简单通用方法:
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());
}
然后:
var enums = EnumHelper.ToList<MyEnum>();