Reputation: 10805
How to convert all elements from enum to string?
Assume I have:
public enum LogicOperands {
None,
Or,
And,
Custom
}
And what I want to archive is something like:
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"
Upvotes: 41
Views: 29484
Reputation: 897
A simple and generic way to convert a enum to something you can interact:
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());
}
and then:
var enums = EnumHelper.ToList<MyEnum>();
Upvotes: 0
Reputation: 26426
You have to do something like this:
var sbItems = new StringBuilder()
foreach (var item in Enum.GetNames(typeof(LogicOperands)))
{
if(sbItems.Length>0)
sbItems.Append(',');
sbItems.Append(item);
}
Or in Linq:
var list = Enum.GetNames(typeof(LogicOperands)).Aggregate((x,y) => x + "," + y);
Upvotes: 14
Reputation: 56381
Although @Moose's answer is the best, I suggest you cache the value, since you might be using it frequently, but it's 100% unlikely to change during execution -- unless you're modifying and re-compiling the enum. :)
Like so:
public static class LogicOperandsHelper
{
public static readonly string OperandList =
string.Join(",", Enum.GetNames(typeof(LogicOperands)));
}
Upvotes: 1
Reputation: 16508
string LogicOperandsStr
= Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=>
current + "," + next);
Upvotes: 2
Reputation: 13974
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
str = str + "," + value;
}
Upvotes: 0