Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get comma separated list of enumeration's integers

Tags:

c#

This:

string csvEnums = string.Join(",", Enum.GetNames(typeof(Bla)));

returns:

X1,Y1

given this enumeration:

public enum Bla
{
    [Description("X")]
    X1 = 1,
    [Description("Y")]
    Y1 = 2
}

Is there a similar efficient way to obtain the comma separated list:

1,2
like image 556
cs0815 Avatar asked Dec 18 '22 18:12

cs0815


2 Answers

Try casting GetValues() return array to ints:

string csvEnums = string.Join(",", Enum.GetValues(typeof(Bla)).Cast<int>());

The problem with GetValues() method is that returns an object of type Array, and there are no Join() overload that can process it correctly.

like image 88
Arturo Menchaca Avatar answered Jan 03 '23 16:01

Arturo Menchaca


Try this:

string csvEnums = string.Join(",", Enum.GetValues(typeof(Bla)).Cast<Bla>().Select(x=>(int)x));
like image 36
Tamas Ionut Avatar answered Jan 03 '23 16:01

Tamas Ionut