C # - how to check if the byte value matches any flags in the specified enum flag?

In C #, I store the flag enumeration value in the database as a byte. For example, for the following flag enumeration:

[Flags]
public enum Options
{
    None = 0,
    First = 1,
    Second = 2,
    Third = 4
}

If I want to write “First” and “Second”, I save this as byte “3” in the “Parameters” field of the record in the database.

So, when using LINQ, how can I check if the value in the "any" database matches the parameters in the argument passed as the "parameter enumeration", something like this pseudocode:

    public static Something(Options optionsToMatch)
    {
       db.MyEntity.Get(a => a.options contains any of the options in optionsToMatch);
+4
source share
2 answers

, , , ( ).

   static void Main()
    {
        //stand-in for my database
        var options = new byte[] { 1, 2, 3, 3, 2, 2, 3, 4, 2, 2, 1,5 };

        var input = (Options)5;

        //input broken down into a list of individual flags
        var optional = GetFlags(input).ToList();
        //get just the options that match either of the flags (but not the combo flags, see below)
        var foundOptions = options.Where(x => optional.Contains((Options)x)).ToList();
        //foundOptions will have 3 options: 1,4,1
    }

    static IEnumerable<Enum> GetFlags(Enum input)
    {
        foreach (Enum value in Enum.GetValues(input.GetType()))
            if (input.HasFlag(value))
                yield return value;
    }

5 ( ), , :

var foundOptions = options.Where(x => optional.Contains((Options)x) || input == (Options)x).ToList();
+1

. , .

[Flags]
enum opts : byte {
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
    D = 1 << 3,
    //.. etc
}

, 0

opts a = opts.A | opts.D;
opts b = opts.B | opts.C | opts.D;
var c = a & b; //D

if((byte)c!=0){
    // ... things
}
0

Source: https://habr.com/ru/post/1652397/


All Articles