2

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

Pavel
  • 1,015
  • 3
  • 13
  • 27
  • 1
    possible duplicate of [How do I enumerate an enum in C#?](http://stackoverflow.com/questions/105372/how-do-i-enumerate-an-enum-in-c) – Nikola Oct 10 '14 at 13:34
  • @Nikola Not a duplicate of that. Here, there is a concrete list to iterate over. –  Oct 10 '14 at 13:34
  • @Nikola Thanks. http://stackoverflow.com/questions/105372/how-do-i-enumerate-an-enum-in-c/944352#944352 this answer was helpful. – Pavel Oct 10 '14 at 13:41

2 Answers2

4
EnumTest result = 0;

foreach (EnumTest et in values)
{
   result |= et;
}
4

Here's a solution using Linq:

var result = values.Aggregate((x, y) => x |= y);
brz
  • 5,926
  • 1
  • 18
  • 18