Search code examples
c#dynamic-linq

C# Dynamic Linq - Case Statements


I'm having some trouble with Dynamic Linq and I was hoping that someone could help. The problem I'm facing is that I need to order a list in a specific sequence. In SQL I would write this as:

ORDER BY CASE WHEN Blah = 'blah' THEN 1 ELSE 0 END

How would I accomplish this with Dynamic Linq?

I've tried something like:

listToSort.AsQueryable().OrderBy("CASE WHEN Blah = 'blah' THEN 1 ELSE 0 END")

But this returns an error

No property or field 'CASE' exists in type

This code is generated at runtime as a list of expressions. So I'm using Dynamic Linq to make use of the expessions as a string.


Solution

  • You can use the conditional operator:

    listToSort.AsQueryable()
        .OrderBy(x => x.Blah == "blah" ? 1 : 0); 
    

    You could also use this since a true is "more" than a false:

    listToSort.AsQueryable()
        .OrderBy(x => x.Blah == "blah"); 
    

    It seems that in dynamic LINQ CASE or the conditional operator are not supported. But there is another keyword you can use: iif

    listToSort.AsQueryable()
        .OrderBy("iif(Blah = 'blah', 1, 0)"); 
    

    Overview of the dynamic LINQ expression methods and keywords.