0

I have a list of strings in an xml document:

<properties>red yellow blue</properties>

and I have an enum:

[Flags]
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 7 or 0111?

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.

leigero
  • 3,233
  • 12
  • 42
  • 63
  • Are you asking to create a compile-time construct at runtime? You might be able to do this with reflection, but I'm sure there's probably an alternative to `enum`s here. – PC Luddite Aug 17 '16 at 17:18

2 Answers2

4

Yes, but you need them to be comma separated:

[Flags]
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.

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
1

Sure

string flags = "red yellow blue";

var eflags = flags.Split()
                  .Select(s => (Properties)Enum.Parse(typeof(Properties), s))
                  .Aggregate((a, e) => a | e);

Console.WriteLine(eflags);
Console.WriteLine((int)eflags);

Outpus

red, yellow, blue

7

I'll leave how to get the string out of the xml up to you.

Community
  • 1
  • 1
juharr
  • 31,741
  • 4
  • 58
  • 93
  • 2
    That's got to be the fastest down vote I've ever seen. – juharr Aug 17 '16 at 17:21
  • Apparently someone is on a down vote spree... I got one instantly too. Why do I even both with this site lol? – SledgeHammer Aug 17 '16 at 17:23
  • @SledgeHammer Now I've watched it go back and forth between an up vote and a down vote 3 or 4 times. Kinda funny. – juharr Aug 17 '16 at 17:25
  • This looks to be exactly what I am in need of so I don't understand the down-vote personally. Perhaps someone will chime in as to why this is a bad answer. – leigero Aug 17 '16 at 17:27
  • @leigero, if you look at my answer, Enum has this built in, so all this linq stuff is a bit over kill and a performance hit if you call repeatedly. Not sure if that was the reason... but randomly all the votes went to 0 lol. Might be a site bug or something. – SledgeHammer Aug 17 '16 at 17:28
  • @SledgeHammer It's not a bug, someone is voting and unvoting for some reason. – PC Luddite Aug 17 '16 at 17:30