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?

lukiffer
  • 11,025
  • 8
  • 46
  • 70
Kanvas
  • 165
  • 2
  • 7
  • 23
  • 1
    http://stackoverflow.com/questions/1426577/how-to-use-flags-enums-in-linq-to-entities-queries – Habib May 08 '12 at 07:58

1 Answers1

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);
Stephen Turner
  • 7,125
  • 4
  • 51
  • 68
RePierre
  • 9,358
  • 2
  • 20
  • 37