leigero leigero - 1 year ago 144
C# Question

Is there a way to convert from a list of strings to an enum flag in c#?

I have a list of strings in an xml document:

<properties>red yellow blue</properties>

and I have an enum:

public enum Properties
None = 0,
red = 1,
yellow = 2,
blue = 4,
green = 8

Is there a way to convert the XML string into the enum flag value of

There are countless resources around about doing the reverse of this, but I'm having trouble finding any information on converting from a string to Flags.

Answer Source

Yes, but you need them to be comma separated:

public enum Test
    A = 1,
    B = 2,
    C = 4

Test t;
Enum.TryParse<Test>("A,B", out t);

Since you can't have spaces in the names, you can just do a string replace of space to comma before calling TryParse.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download