Conditional Group By RRS feed

  • Question

  • Hey,


    Is it possible to get Linq To Sql to generate a case statement in a group by?  I want to group depending on a certain condition.  I've tried grouping using the ?: operator but it ends up generating another select.




    Tuesday, November 4, 2008 6:00 PM

All replies

  • You can use ?: in L2S.  This maps directly to SQL CASE expression.  Possibly there is something else going on that is causing additional select's.  L2S may be pre-computing the group-by expression in a nested select. If this is the case, then the query is formed correctly.

    Tuesday, November 4, 2008 6:15 PM
  • Thank you for your response.  Right now I have a very simple query, something like (this sample makes no real sense, I was just trying to come up with a really simple query):


    var personGroupQueryable =

    from person in context.Person

    group person by (person.FirstName == person.MiddleName ? 0 : person.Age) into personGroup

    select personGroup;


    and it still does a select from another select instead of a case in the group by.  Is this intentional from some sort of efficiency perspective (I'm not strong with SQL itself so I'm not sure which is more efficient)?

    Tuesday, November 4, 2008 6:36 PM