4

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?

1

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Enum.IsDefined can be used to avoid ArgumentException
@Tilak, thank you. The updated version can be found at pastebin.com/pyQ9xPv5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.