Getting common flags enum value in c#

前端 未结 4 1938
长发绾君心
长发绾君心 2021-01-23 10:45

Say I have the below enum

[Flags]
enum Letters
{
     A = 1,
     B = 2,
     C = 4,
     D = 8,
     E = 16,
     F = 32,
     AB = A | B,
     All = A | B | C,         


        
相关标签:
4条回答
  • 2021-01-23 11:19

    Here is the result:

        var result =  s & p;
    
    0 讨论(0)
  • 2021-01-23 11:22

    Just as you use | to get a union of values, you can use the & to get the intersection:

    var s = Letters.A | Letters.B | Letters.D;
    var p = Letters.A | Letters.C | Letters.D | Letters.E;
    
    var intersection = s & p;  // A | D
    var union = s | p;         // All | D | E
    
    0 讨论(0)
  • 2021-01-23 11:26

    If that's suitable for you it will return List of individual flags

     static IEnumerable<Enum> GetFlags(Enum input)
        {
            foreach (Enum value in Enum.GetValues(input.GetType()))
                if (input.HasFlag(value))
                    yield return value;
        }
    
    GetFlags(s).Intersect(GetFlags(p))
    
    0 讨论(0)
  • 2021-01-23 11:32

    You can get that using the binary & (and) operator:

    var s = Letters.A | Letters.B | Letters.D;
    var p = Letters.A | Letters.C | Letters.D | Letters.E;
    var sAndp = s & p; // This will give you only the common values ( A & D)
    
    0 讨论(0)
提交回复
热议问题