Is there an easy way to convert a C # enum to a string and vice versa?

I need to convert a list of enum values ​​to a single line for storage in my db; then convert back when i get from the database.

Each enumeration value is currently a prime integer, so you need to outsmart a little to create an additional table.

So, in the example below, if the user selects Mother, Father and Sister, then the value stored in the database will be "0,1,3"

  public enum MyEnum
    {
        Mother = 0,
        Father = 1,
        Gran = 2,
        Sister = 3,
        Brother = 4
    }

I'm new to C #, so I'm not sure if there is a good way to do this - I could not find anything obvious when hunting Google!

Greetings in advance :) - L

+3
source share
8 answers

Enum "0,1,3" :

MyEnum[] selection = { MyEnum.Mother, MyEnum.Father, MyEnum.Sister };

string str = string.Join(",", selection.Cast<int>());

MyEnum[] enm = str.Split(',').Select(s => int.Parse(s)).Cast<MyEnum>().ToArray();
+3

Enum /

int value = (int)MyEnum.Mother;

   MyEnum value = (MyEnum)1;

ToString Enum.Parse

string value = MyEnum.Mother.ToString();

MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum),"Mother");
+8

:

[Flags]
public enum MyEnum
    {
        Mother = 1,
        Father = 2,
        Gran = 4,
        Sister = 8,
        Brother = 16,
    }

, 6

24 ..

, ,

+4

ToString Enum.TryParse ( Enum.Parse, .NET 4) .

, enum (, MyEnum.Mother | MyEnum.Father), Flags enum, @WraithNath . , ( Mother Father ).

+3

MyEnum a = MyEnum.Mother;
string thestring = a.ToString();
MyEnum b = (MyEnum) Enum.Parse(typeof(MyEnum), thestring);
+2

MyEnum value = MyEnum.Father;
value.ToString(); // prints Father

(MyEnum)Enum.Parse(typeof(MyEnum), "Father"); // returns MyEnum.Father
+1

Enum . , , .

, ToString "" "" "" .. :

private MyEnum GetEnumValue(string fromDB)
{
    if( fromDB == "Mother" ) return MyEnum.Mother;
    else if( fromDB == "Father") return MyEnum.Father;
    //etc. etc.
}

EDIT: - "# -ey" ( ).

0

( ), , :

if (Enum.IsDefined(typeof(MyEnum), <your database value>))
{
    // Safe to convert your enumeration at this point:
    MyEnum value = (MyEnum)1;   
}
0

Source: https://habr.com/ru/post/1788198/


All Articles