如何使用标志检查集合中的某些内容是否与标志匹配

How to use flags to check if something from the collection matches the flag

我正在尝试使用标志来过滤集合并检索某些对象。

也许示例会显示问题。

我定义了一个 class 和一个枚举。

    public class ExampleFlagsDto
{
    public int FlagId { get; set; }
    public string Name { get; set; }

}


[Flags]
public enum FlagsTypes
{
    None = 0,
    Small = 1 << 0 ,
    Medium = 1 << 1 ,
    Normal = 1 << 2,
    Large = 1 << 3,
    LargeAndNormal = Normal | Large,
    All = Normal | Medium | Small | Large,

}

然后我构建了一个列表作为示例,并尝试从列表中检索 2 个对象。

   var examples = new List<ExampleFlagsDto>()
        {
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Normal,
                Name = "First"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Medium,
                Name = "Second"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Large,
                Name = "Third"
            },
            new ExampleFlagsDto
            {
                FlagId  = (int)FlagsTypes.Small,
                Name = "Forth"
            },
        };

        var selected = examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();


        foreach (var flag in selected)
        {
            Console.WriteLine(flag.Name);
        }

当然不行。我知道当涉及到位时,(int)FlagTypes.LargeAndNormal 会导致 Large 和 Normal 位的总和。不过,我不知道它是如何按位显示的。

我正在寻找一种方法来改变

  examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();

解决方案会导致从示例中选择具有 2 个对象。

您可以尝试这个解决方案:

var selectedAll = examples.Where(C => (C.FlagId & (int)FlagsTypes.All) == (int)C.FlagId).ToList();