给定以下枚举:
[Flags]
public enum CheeseCharacteristic
{
Yellow = 1,
Stinks = 2,
Squeaks = 4,
Holey = 8,
Mouldy = 16,
UseOnToast = 32
}
还有一个实体 Cheese
具有 Characteristic
属性,是否可以根据与 Characteristic
匹配的标志数量来订购 Cheese?例如,假设 Stilton
具有 Characteristic
值 Yellow
、Stinks
、Mouldy
并且 MildCheddar
具有 Characteristic
值 Yellow
,UseOnToast
,是否可以按匹配次数排序给定的查询?
因此,如果我想将一组 Cheese
实体与 Yellow
、Mouldy
进行比较,那么 Stilton
和MildCheddar
被返回,但是 Stilton
是列表的顶部,因为它有 2 个匹配项。
更进一步,如果我将枚举值存储在 SQL Server 中,我可以使用 EF Core 在数据库中执行这种排序吗?
最佳答案
我喜欢这个版本,因为它在处理任何位掩码枚举时都保持类型安全。
using System;
using System.Linq;
using System.Collections.Generic;
namespace SO_58416947_count_bitmask_flags {
static class Program {
[Flags]
public enum CheeseCharacteristics {
Yellow = 1,
Stinky = 2,
Squeaky = 4,
Holey = 8,
Mouldy = 16,
Spreadable = 32,
UseOnToast = Yellow | Spreadable
}
static void Main(string[] args) {
List<CheeseCharacteristics> _testCases = new List<CheeseCharacteristics>() {
{CheeseCharacteristics.UseOnToast | CheeseCharacteristics.Stinky},
{CheeseCharacteristics.Yellow | CheeseCharacteristics.Holey}, // Swiss
{CheeseCharacteristics.Squeaky},
{CheeseCharacteristics.Mouldy | CheeseCharacteristics.Spreadable}
};
List<CheeseCharacteristics> cases = _testCases.OrderByFlagCount();
foreach(CheeseCharacteristics c in cases) {
Console.WriteLine($"{c}");
}
} // Main()
private static List<T> GetIndividualFlagValues<T>() where T:Enum {
Type enumType = typeof(T);
if (!enumType.IsEnum) { throw new ArgumentException("Must pass an enum type."); }
List<T> result = new List<T>();
foreach(T item in Enum.GetValues(enumType)) {
result.Add(item);
}
return result;
} // GetIndividualFlagValues()
//extension method
public static List<T> OrderByFlagCount<T>(this List<T> list) where T:Enum {
List<T> flags = GetIndividualFlagValues<T>();
List<T> results = list
.OrderBy(t => flags.Where(f => true == t.HasFlag(f)).Count())
.ToList();
return results;
}
} // Program
} // ns
关于c# - ORDER BY C# 枚举标志最匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416947/