36

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"
Keltex
  • 26,220
  • 11
  • 79
  • 111
Maciej
  • 10,423
  • 17
  • 64
  • 97

6 Answers6

86
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));
Moose
  • 5,354
  • 3
  • 33
  • 46
13

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);
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
Keltex
  • 26,220
  • 11
  • 79
  • 111
2
string LogicOperandsStr 
     = Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=> 
                                                       current + "," + next);
Vivek
  • 16,360
  • 5
  • 30
  • 37
1

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)));
}
Randolpho
  • 55,384
  • 17
  • 145
  • 179
0

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>();
Gabriel
  • 887
  • 10
  • 22
0
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
    str = str + "," + value;
}
CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58