I'm not really sure if I have the correct title for this Q. anyway I'm trying to parse a delimited string into a list of Enum elements:
public enum MyEnum { Enum1, Enum2, Enum3 }
Given an input of:
string s = "Enum2, enum3, Foo,";
I would like to output only the parts that exists in MyEnum (ignoring the case):
[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 ??? })
How do I return "nothing" from the Select() if TryParse() fails?
I could do an ugly thing like:
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));
Doing the parsing job twice for no good reason,
But I'm sure I'm missing something trivial.
How can this be done in an efficient and elegant way?