Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert IEnumerable<Enum> to Enum in C#?

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?

like image 868
waj Avatar asked Aug 07 '11 12:08

waj


People also ask

How do I return an enum list?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

How do I find the enum of a number?

You can use: int i = Convert. ToInt32(e); int i = (int)(object)e; int i = (int)Enum. Parse(e.

What is enum parse?

Enum.TryParse Method (System)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

How do I assign an int to an enum?

Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .


1 Answers

Well, from an IEnumerable<MyEnum> you can use:

MyEnum result = parsed.Aggregate((current, next) => current | next);

or in order to accommodate an empty sequence:

MyEnum result = parsed.Aggregate(MyEnum.None, (current, next) => current | next);

It's basically the same thing as you've already got, admittedly...

So overall, the code would be:

MyEnum result = flags.Select(x => (MyEnum) Enum.Parse(typeof(MyEnum), x))
                     .Aggregate(MyEnum.None, (current, next) => current | next);

(You can perform it in a single Aggregate call 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.TryParse method in .NET 4.

So for example, using Unconstrained Melody you could use:

MyEnum result = flags.Select(x => Enums.ParseName<MyEnum>(x))
                     .Aggregate(MyEnum.None, (current, next) => current | next);
like image 68
Jon Skeet Avatar answered Oct 08 '22 07:10

Jon Skeet