开发者

Flags and enum to make an linq anyFlags(MyFlag)

this is a basic question I know , and surely a redo of some old recipe made by everyone on planet earth and beyond, but I just get so lost that I need some external advice.

I have an enum like this one :

[Flags]
    public enum MyEnum
    { 
        none=0,  //0000
        toto=1,  //0001
        tata=2,  //0010
        tati=4,  //0100
        titi=8   //1000
    }

and I have an enum value which is like :

MyEnum s= tata | titi; //(1010) 

so as to say from what I understood s=10

Now I have a value in my database wich is a short and might be one of these , ie: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

id     EnumValue
1      3
2      14
3      10
4      9
5      0

Now I need to get a linq statement to say which id have at least one othe enum given in s.

I would need at the end :1,2,3,4.

I have done so for theses method :

public static bool HasAllFlags(this short input, Enum matchTo)
{
    return (Convert.ToUInt32(input) & Convert.ToUInt32(matchTo)) == Convert.ToUInt32(matchTo);
}

public static bool IsFlag(this short input, Enum matchTo)
{
    return Convert.ToUInt32(input)== Convert.ToUInt32(matchTo);
}

but I am stuck开发者_JAVA技巧 with this one :

 public static bool HasAnyFlags(this short input, Enum matchTo)
        {
            return ....????....;
        }

They work pretty well , but I now I need this method which would give me 1,2,3,4 as the desired result. I have tried quite a few things but I cannot get it right. Has any of you any solutions ready made for this?

Thanks in advance,

PS: I am using c# 3.5


How about just comparing with (Enum) 0 ?


Consider your HasAllFlags method. It performs a bitwise AND on the test value and the required value. The result of this will be a value where each bit is set if-and-only-if it is set in the test value AND it is a required value. By checking this result value against the set of all required flags, you get your answer.

However, this same result value can also be used to check if any of the required flags were present. If any of the required flags were present, this result value will be non-zero. So all we need is

public static bool HasAnyFlags(this short input, Enum matchTo)
{
    return (Convert.ToUInt32(input) & Convert.ToUInt32(matchTo)) 
             != Convert.ToUInt32(0);
}

(Note that the behaviour if matchTo is 0 might not be what you expect)

Examples (in binary):

input    101010
matchTo  001100
result   001000 -> nonzero -> true

input    101010
matchTo  010001
result   000000 -> zero -> false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜