如何转换IEnumerable的<&枚举GT;在C#中枚举? [英] How do I convert IEnumerable<Enum> to Enum in C#?

查看:208
本文介绍了如何转换IEnumerable的<&枚举GT;在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);



我使用的是选择方法转换到我的枚举类型的尝试,但后来我卡与的IEnumerable< MyEnum> 。 ?任何建议

推荐答案

那么,从的IEnumerable< MyEnum> 你可以使用:

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);



(您可以在一个单一的总结呼叫按Guffa的答案,但我个人认为我会保持两个独立的,为了清楚,这是一个个人喜好,但。)

(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.)

请注意我的无约束的旋律项目使得枚举处理较为愉快,你也可以使用通用的 Enum.TryParse 在.NET 4的方法。

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);

这篇关于如何转换IEnumerable的&LT;&枚举GT;在C#中枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆