views:

1264

answers:

5

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"
A: 
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
    str = str + "," + value;
}
CookieOfFortune
You're missing the commas
Keltex
+9  A: 

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);
Keltex
I was thinking of the similar linq version, you beat me. +1
Vivek
Please don't abuse StringBuilder like that!
Randolpho
Randolpho what's wrong with the stringbuilder code ? What abuse ?
Petar Petrov
Indeed, it looks okay to me. Using String.Join is neater, but I don't see any "abuse" here.
Jon Skeet
Unless you've got dozens of items in the enumeration, you're better off with a string concatenation.
Randolpho
Further reading: http://stackoverflow.com/questions/529999/when-to-use-string-builder/530007
Randolpho
Wait... didn't you write the correct answer to that Jon? This is a trivial loop. StringBuilder is overkill.
Randolpho
+21  A: 
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));
Moose
+1  A: 
string LogicOperandsStr 
     = Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=> 
                                                       current + "," + next);
Vivek
+1  A: 

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