Getting common flags enum value in c#

让人想犯罪 __ 提交于 2020-12-26 12:26:28

问题


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,
}

If I have the variables:

var s = Letters.A | Letters.B | Letters.D;
var p = Letters.A | Letters.C | Letters.D | Letters.E;

What I want is to get the common values between these two enums so in this case it should be A | D. Can some one please tell me how I can achieve this.

Thanks


回答1:


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)



回答2:


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



回答3:


Here is the result:

    var result =  s & p;



回答4:


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))


来源:https://stackoverflow.com/questions/51975514/getting-common-flags-enum-value-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!