2009-04-10 124 views
20

如何将所有元素从枚举转换为字符串?所有枚举项到字符串(C#)

假设我有:

public enum LogicOperands { 
     None, 
     Or, 
     And, 
     Custom 
} 

而我想存档是一样的东西:

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

检查这个答案可能也有用:https://stackoverflow.com/a/12022617/1830909 – QMaster 2017-11-22 16:53:15

回答

56
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands))); 
0
foreach (string value in Enum.GetNames(typeof(LogicOoperands)) 
{ 
    str = str + "," + value; 
} 
+0

你错过了逗号 – Keltex 2009-04-10 15:08:56

+0

你必须修剪最后一个逗号 – Yargicx 2018-02-08 18:23:26

11

你必须做这样的事情:

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
string LogicOperandsStr 
    = Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=> 
                 current + "," + next); 
1

虽然@驼鹿的回答是最好的,我建议你缓存值,因为你可能会经常使用它,但它不可能100%的执行过程中改变 - 除非你修改和重新编译枚举。 :)

像这样:

public static class LogicOperandsHelper 
{ 
    public static readonly string OperandList = 
    string.Join(",", Enum.GetNames(typeof(LogicOperands))); 
} 
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>();