I’ve parsed several strings into Enum flags but can’t see a neat way of merging them into a single Enum bitfield.
The method I’m using loops through the string values then |= the casted values to the Enum object, like so:
[Flags]
public enum MyEnum { None = 0, First = 1, Second = 2, Third = 4 }
...
string[] flags = { "First", "Third" };
MyEnum e = MyEnum.None;
foreach (string flag in flags)
e |= (MyEnum)Enum.Parse(typeof(MyEnum), flag, true);
I’ve tried using a Select method to convert to my Enum type, but then I’m stuck with IEnumerable<MyEnum>. Any suggestions?
Well, from an
IEnumerable<MyEnum>you can use:or in order to accommodate an empty sequence:
It’s basically the same thing as you’ve already got, admittedly…
So overall, the code would be:
(You can perform it in a single
Aggregatecall as per Guffa’s answer, but personally I think I’d keep the two separate, for clarity. It’s a personal preference though.)Note that my Unconstrained Melody project makes enum handling somewhat more pleasant, and you can also use the generic
Enum.TryParsemethod in .NET 4.So for example, using Unconstrained Melody you could use: