[英]How to use flags to check if something from the collection matches the flag
我正在尝试使用标志来过滤集合并检索某些对象。
也许这个例子会说明这个问题。
我定义了一个类和一个枚举。
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 会导致大和正常的位总和。 不过,我不知道它必须如何按位显示。
我正在寻找一种方法来改变
examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();
到一个解决方案,该解决方案将导致从示例中选择 2 个对象。
你可以试试这个解决方案:
var selectedAll = examples.Where(C => (C.FlagId & (int)FlagsTypes.All) == (int)C.FlagId).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.