Search code examples
c#enum-flags

Set value to [Flags] Enum from list c#


I need to set the Enum value by items taken from the list.

I have Enum:

[Flags]
public enum EnumTest
{
    Val1= 1, 

    Val2= 2, 

    Val3= 4
}

List with values:

var values = new List<EnumTest> {EnumTest.Val1, EnumTest.Val3};

How can I get the following result using a foreach?

var result = EnumTest.Val1 | EnumTest.Val3;

Thanks


Solution

  • Here's a solution using Linq:

    var result = values.Aggregate((x, y) => x |= y);