Convert string to enum in Linq to SQL

How to convert string to enum in Linq using C #?

Does listing below like in linq also work ?:

(Audience)Enum.Parse(typeof(Audience), value, true);

If yes, please tell me how can I use this?

+3
source share
1 answer

Given the listing

enum Foo{A, B, C}

the code below converts from enumto stringand vice versa:

var values = 
from name in Enum.GetNames(typeof(Foo))
select (Foo)Enum.Parse(typeof(Foo), name, true);

So yes, casting works. However, keep in mind that the above request will call the method ArgumentExceptionif the method Enum.Parsereceives a value that cannot be parsed.

This updated version only returns values ​​that are processed successfully.

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);
+6
source

All Articles