C# Linq 查询选择以 String 开头的所有枚举

Ila*_*het 3 c# linq

我有一个enum, 我想找到enum以传入字符串开头的所有匹配值(不区分大小写)

例子:

enum Test
{
   Cat,
   Caterpillar,
   @Catch,
   Bat
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我指定"cat"此 Linq 查询,它将选择Test.Cat, Test.Caterpillar,Test.Catch

spe*_*der 5

Enum.GetValues(typeof(Test)) //IEnumerable but not IEnumerable<Test>
    .Cast<Test>()            //so we must Cast<Test>() for LINQ
    .Where(test => Enum.GetName(typeof(Test), test)
                       .StartsWith("cat", StringComparison.OrdinalIgnoreCase))
Run Code Online (Sandbox Code Playgroud)

或者如果你真的很想这么做,你可以提前准备一个前缀查找

ILookup<string, Test> lookup = Enum.GetValues(typeof(Test)) 
    .Cast<Test>() 
    .Select(test => (name: Enum.GetName(typeof(Test), test), value: test))
    .SelectMany(x => Enumerable.Range(1, x.name.Length)
                               .Select(n => (prefix: x.name.Substring(0, n), x.value) ))
    .ToLookup(x => x.prefix, x => x.value, StringComparer.OrdinalIgnoreCase)
Run Code Online (Sandbox Code Playgroud)

所以现在你可以

IEnumerable<Test> values = lookup["cat"];
Run Code Online (Sandbox Code Playgroud)

在 zippy O(1) 时间内消耗一点内存。可能不值得!