C#Linq查询选择以字符串开头的所有枚举
我有一个C#Linq查询选择以字符串开头的所有枚举,c#,linq,C#,Linq,我有一个enum,我想查找enum中以传入字符串开头的所有匹配值(不区分大小写) 例如: enum Test { Cat, Caterpillar, @Catch, Bat } 例如,如果我为此Linq查询指定“cat”,它将选择Test.cat,Test.caterpiller,Test.CatchEnum.GetValues(typeof(Test))//IEnumerable但不IEnumerable Enum.GetValues(typeof(Test)) //
enum
,我想查找enum
中以传入字符串开头的所有匹配值(不区分大小写)
例如:
enum Test
{
Cat,
Caterpillar,
@Catch,
Bat
}
例如,如果我为此Linq查询指定“cat”
,它将选择Test.cat
,Test.caterpiller
,Test.Catch
Enum.GetValues(typeof(Test))//IEnumerable但不IEnumerable
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))
.Cast()//因此我们必须对LINQ执行Cast()
.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)
ILookup lookup=Enum.GetValues(typeof(Test))
.Cast()
.Select(test=>(名称:Enum.GetName(typeof(test),test),value:test))
.SelectMany(x=>Enumerable.Range(1,x.name.Length)
.Select(n=>(前缀:x.name.Substring(0,n),x.value)))
.ToLookup(x=>x.prefix,x=>x.value,StringComparer.OrdinalIgnoreCase)
所以现在你可以
IEnumerable<Test> values = lookup["cat"];
IEnumerable values=lookup[“cat”];
在快速的O(1)时间中,以牺牲一点内存为代价。可能不值得
Catch
是一个保留令牌,因此必须使用@
进行预处理。哎呀,那完全是个意外。。。我将此作为示例-(在我的代码中不是实际的)