Line | |
---|
1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Problems.ProgramSynthesis { |
---|
6 | public static class EnumExtensions {
|
---|
7 | public static T ToMask<T>(this IEnumerable<T> values) where T : struct, IConvertible {
|
---|
8 | if (!typeof(T).IsEnum)
|
---|
9 | throw new ArgumentException("T must be an enumerated type.");
|
---|
10 |
|
---|
11 | var builtValue = Enum
|
---|
12 | .GetValues(typeof(T))
|
---|
13 | .Cast<T>()
|
---|
14 | .Where(values.Contains)
|
---|
15 | .Aggregate(0, (current, value) => current | Convert.ToInt32(value));
|
---|
16 |
|
---|
17 | return (T)Enum.Parse(typeof(T), builtValue.ToString());
|
---|
18 | }
|
---|
19 |
|
---|
20 | public static IEnumerable<T> ToValues<T>(this T flags) where T : struct, IConvertible {
|
---|
21 | if (!typeof(T).IsEnum)
|
---|
22 | throw new ArgumentException("T must be an enumerated type.");
|
---|
23 |
|
---|
24 | var inputInt = (int)(object)flags;
|
---|
25 | foreach (T value in Enum.GetValues(typeof(T))) {
|
---|
26 | var valueInt = (int)(object)value;
|
---|
27 | if (0 != (valueInt & inputInt)) {
|
---|
28 | yield return value;
|
---|
29 | }
|
---|
30 | }
|
---|
31 | }
|
---|
32 | }
|
---|
33 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.