仅当 LINQ 中有条件时才选择

zig*_*zig 5 c# linq

我不确定我是否有这个 Q 的正确标题。无论如何,我正在尝试将分隔字符串解析为 Enum 元素列表:

public enum MyEnum { Enum1, Enum2, Enum3 }
Run Code Online (Sandbox Code Playgroud)

给定输入:

string s = "Enum2, enum3, Foo,";
Run Code Online (Sandbox Code Playgroud)

我只想输出MyEnum(忽略大小写)中存在的部分:
[MyEnum.Enum2, MyEnum.Enum3]

IEnumerable<MyEnum> sl = 
    s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)                         
    .Select(a => { if (Enum.TryParse(a, true, out MyEnum e)) return e; else return nothing ??? })
Run Code Online (Sandbox Code Playgroud)

如何从Select()ifTryParse()失败中返回“无” ?
我可以做一件丑陋的事情,比如:

IEnumerable<MyEnum> sl = 
    s.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)                
    .Where(a => Enum.TryParse(a, true, out MyEnum dummy))
    .Select(a => Enum.Parse(typeof(MyEnum), a, true));
Run Code Online (Sandbox Code Playgroud)

无缘无故地做两次解析工作,
但我确定我错过了一些微不足道的东西。
如何以一种高效而优雅的方式做到这一点?

Eni*_*ity 5

如果您对以下项使用可为空的值,这将非常简单enum

IEnumerable<MyEnum> sl =
    s
        .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(a => { if (Enum.TryParse(a, true, out MyEnum e)) return (MyEnum?)e; else return null; })
        .Where(x => x.HasValue)
        .Select(x => x.Value);
Run Code Online (Sandbox Code Playgroud)

你甚至可以进一步减少它:

        .Select(a => Enum.TryParse(a, true, out MyEnum e) ? (MyEnum?)e : null)
Run Code Online (Sandbox Code Playgroud)

或者您可以使用SelectMany并避免可空值:

IEnumerable<MyEnum> sl =
    s
        .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
        .SelectMany(a => Enum.TryParse(a, true, out MyEnum e) ? new[] { e } : new MyEnum[] { });
Run Code Online (Sandbox Code Playgroud)