且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换IEnumerable的<&枚举GT;在C#中枚举?

更新时间:2022-01-30 22:08:43

那么,从的IEnumerable&LT; MyEnum&GT; 你可以使用:

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