0

I've been searching about how to convert enums to predicate in lambda expression/LINQ query to EF. For example, I have below enums:

public enum MyEnum
{
  [Display(DisplayName="FirstDesc")
  First = 0,
  [Display(DisplayName="SecondDesc")]
  Second = 1,
  [Display(DisplayName="ThirdDesc")]
  Third = 2
}

And my LINQ query is

var query = (from a in context.users
             select new { Desc = 
             case when Status==(int)MyEnum.First ? "FirstDesc" :
             case when Status==(int)MyEnum.Second ? "SecondDesc":
             case when Status==(int)MyEnum.Third ? "ThirdDesc" : "Unknown" });

I want to achieve that once I add a new item to enum, the linq query automatically adjust the condition to all the items in the Enum.

Any help would be appreciated.

keenthinker
  • 7,645
  • 2
  • 35
  • 45
Darius Iko
  • 249
  • 1
  • 6
  • What's wrong with just adding a helper method? It could even initialize a dictionary based on the DisplayAttribute attribute you've included on the enum so that the string literals don't have to be repeated. – Peter Duniho Oct 18 '14 at 07:35
  • 1
    You might want to grab those attributes instead : http://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value (and scrape off these cases) – aybe Oct 18 '14 at 07:38
  • This EF LINQuery will not compile! There is no such syntax as `case when`. – keenthinker Oct 18 '14 at 07:44

0 Answers0