简体   繁体   中英

C# - how do I check if a byte value matches against any flags in a specified flags enum?

In C#, I'm storing a flags enum value in a database as a byte. For example, for the following Flags enum:

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

If I want to record 'First' and 'Second', I save this as a byte of '3' in the 'options' field of a record in the database.

So when using LINQ, how can I check if the value in the database matches 'any' of the options in an argument passed as an 'Options' enum, something like this pseudocode:

    public static Something(Options optionsToMatch)
    {
       db.MyEntity.Get(a => a.options contains any of the options in optionsToMatch);

Here's code that does what you want by iterating over the enums (I took that answer from here ).

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

EDIT

If you also want to find 5 in this example (the combo of options), just add an extra or condition like so:

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

First, define the flags usefully. A single set bit for each flag, so that they can be easily combined in any combination.

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

Then just bitwise AND and see if it's not equal to 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM