简体   繁体   English

如何在C#中将IEnumerable <Enum>转换为Enum?

[英]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. 我已经将几个字符串解析为Enum标志,但是看不到将它们合并到单个Enum位域的简洁方法。

The method I'm using loops through the string values then |= the casted values to the Enum object, like so: 我正在使用的方法循环遍历字符串值,然后| =枚举值到Enum对象,如下所示:

[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> . 我尝试使用Select方法转换为我的Enum类型,但后来我坚持使用IEnumerable<MyEnum> Any suggestions? 有什么建议?

Well, from an IEnumerable<MyEnum> you can use: 好吧,从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);

(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.) (根据Guffa的回答,你可以在单个Aggregate调用中执行它,但我个人认为,为了清楚起见,我将两者分开。虽然这是个人偏好。)

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. 请注意,我的Unconstrained Melody项目使枚举处理更加愉快,您还可以在.NET 4中使用通用的Enum.TryParse方法。

So for example, using Unconstrained Melody you could use: 例如,使用Unconstrained Melody,您可以使用:

MyEnum result = flags.Select(x => Enums.ParseName<MyEnum>(x))
                     .Aggregate(MyEnum.None, (current, next) => current | next);

You can use the Aggregate method to put the flags together: 您可以使用Aggregate方法将标记放在一起:

MyEnum e = flags
  .Select(s => (MyEnum)Enum.Parse(typeof(MyEnum), s, true))
  .Aggregate(MyEnum.None, (f, n) => f | n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM