[英]C# - how do I check if a byte value matches against any flags in a specified flags enum?
在C#中,我將標記枚舉值作為字節存儲在數據庫中。 例如,對於以下Flags枚舉:
[Flags]
public enum Options
{
None = 0,
First = 1,
Second = 2,
Third = 4
}
如果我想記錄'First'和'Second',我將其保存為數據庫中記錄的'options'字段中的'3'字節。
因此,在使用LINQ時,如何檢查數據庫中的值是否與作為“選項”枚舉傳遞的參數中的“任何”選項匹配,類似於此偽代碼:
public static Something(Options optionsToMatch)
{
db.MyEntity.Get(a => a.options contains any of the options in optionsToMatch);
這里的代碼通過迭代枚舉來完成你想要的東西(我從這里得到了答案)。
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();
首先,有用地定義標志。 每個標志的單個位設置,以便它們可以輕松組合成任意組合。
[Flags]
enum opts : byte {
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
//.. etc
}
然后只是按位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.