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

时间:2018-09-23 01:38:25

标签: c# linq

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

示例:

enum Test
{
   Cat,
   Caterpillar,
   @Catch,
   Bat
}

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

1 个答案:

答案 0 :(得分:3)

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))

或者,如果您真的要对此进行锤击,则可以提前准备前缀查找

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)

现在您可以

IEnumerable<Test> values = lookup["cat"];
在zippy O(1)时间中

会浪费一些内存。可能不值得!