Convert array of enum values to bit-flag combination

int result = 0;
foreach (MyEnum f in flags)
{
    result |= f; // You might need to cast — (int)f.
}
return result;

OTOH, you should use the FlagsAttribute for improved type safety:

[Flags]
enum MyEnum { ... }

private MyEnum ConvertToBitFlags(MyEnum[] flags)
{
    MyEnum result = 0;
    foreach (MyEnum f in flags)
    {
        result |= f;
    }
    return result;
}

Better still, by using FlagsAttribute you may be able to avoid using a MyEnum[] entirely, thus making this method redundant.


Here's a shorter generic extension version:

public static T ConvertToFlag<T>(this IEnumerable<T> flags) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new NotSupportedException($"{typeof(T).ToString()} must be an enumerated type");

    return (T)(object)flags.Cast<int>().Aggregate(0, (c, n) => c |= n);
}

And using:

[Flags]
public enum TestEnum
{
    None = 0,
    Test1 = 1,
    Test2 = 2,
    Test4 = 4
}

[Test]
public void ConvertToFlagTest()
{
    var testEnumArray = new List<TestEnum> { TestEnum.Test2, TestEnum.Test4 };

    var res = testEnumArray.ConvertToFlag();

    Assert.AreEqual(TestEnum.Test2 | TestEnum.Test4, res);
}

Tags:

C#

C# 2.0