Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All Enum items to string (C#)

Tags:

c#

.net

enums

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" 
like image 686
Maciej Avatar asked Apr 10 '09 15:04

Maciej


People also ask

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can I convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.


2 Answers

string s = string.Join(",",Enum.GetNames(typeof(LogicOperands))); 
like image 97
Moose Avatar answered Sep 21 '22 19:09

Moose


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); 
like image 20
Keltex Avatar answered Sep 20 '22 19:09

Keltex