如何将所有元素从枚举转换为字符串?所有枚举项到字符串(C#)
假设我有:
public enum LogicOperands {
None,
Or,
And,
Custom
}
而我想存档是一样的东西:
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"
如何将所有元素从枚举转换为字符串?所有枚举项到字符串(C#)
假设我有:
public enum LogicOperands {
None,
Or,
And,
Custom
}
而我想存档是一样的东西:
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));
你必须做这样的事情:
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);
string LogicOperandsStr
= Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=>
current + "," + next);
虽然@驼鹿的回答是最好的,我建议你缓存值,因为你可能会经常使用它,但它不可能100%的执行过程中改变 - 除非你修改和重新编译枚举。 :)
像这样:
public static class LogicOperandsHelper
{
public static readonly string OperandList =
string.Join(",", Enum.GetNames(typeof(LogicOperands)));
}
一个简单而通用的方法来一个枚举转换为东西,你可以互动:
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>();
检查这个答案可能也有用:https://stackoverflow.com/a/12022617/1830909 – QMaster 2017-11-22 16:53:15