简体   繁体   English

C# - 如何检查字节值是否与指定标志枚举中的任何标志匹配?

[英]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. 在C#中,我将标记枚举值作为字节存储在数据库中。 For example, for the following Flags enum: 例如,对于以下Flags枚举:

[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. 如果我想记录'First'和'Second',我将其保存为数据库中记录的'options'字段中的'3'字节。

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: 因此,在使用LINQ时,如何检查数据库中的值是否与作为“选项”枚举传递的参数中的“任何”选项匹配,类似于此伪代码:

    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: 如果您还想在此示例中找到5(选项的组合),只需添加一个额外的或条件,如下所示:

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 然后只是按位AND,看看它是否不等于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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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