How to convert string to enum in Linq using C#?
Does the type casting below also work in linq?:
(Audience)Enum.Parse(typeof(Audience), value, true);
If yes, please tell me how I can use this?
How to convert string to enum in Linq using C#?
Does the type casting below also work in linq?:
(Audience)Enum.Parse(typeof(Audience), value, true);
If yes, please tell me how I can use this?
Given the enum
enum Foo{A, B, C}
the code below performs conversion from enum
to string
and vice-versa:
var values =
from name in Enum.GetNames(typeof(Foo))
select (Foo)Enum.Parse(typeof(Foo), name, true);
So, yes the casting works. However, keep in mind that the query above will throw an ArgumentException
if Enum.Parse
method receives a value that cannot be parsed.
This updated version only returns values that parse sucessfully
enum Foo{A, B, C}
var values =
from name in Enum.GetNames(typeof(Foo))
where Enum.IsDefined(typeof(Foo), name)
select (Foo)Enum.Parse(typeof(Foo), name, true);