views:

72

answers:

1

using LINQ to NHibernate does anybody know how to use group by and order by in the same expression. I am having to execute the group by into a list and then order this, seem that I am missing soemthing here ???

Example:-

Private function LoadStats(...) ...
  Dim StatRepos As DataAccess.StatsExtraction_vwRepository = New DataAccess.StatsExtraction_vwRepository

  return (From x In StatRepos.GetAnswers(Question, Questionnaire) _
              Group x By xData = x.Data Into Count() _
              Select New ChartData 
                   With {.TheData = xData, 
                         .TheValue = xData.Count}
         ).ToList.OrderBy(Function(x) x.TheData)

End Sub
+1  A: 

I'm not a Visual Basic expert, but you should be able to use alias in the Select clause to create a temporary variable, so that you can refer to it in a later clauses such as Order By. Unless there is some limitation in NHibernate, the following should work:

return From x In StatRepos.GetAnswers(Question, Questionnaire) _ 
       Group x By xData = x.Data Into Count() _ 
       Select res = New ChartData With _
         { .TheData = xData,  _
           .TheValue = xData.Count } _
       Order By res.TheData _
       Select res

I guess that in some situations, this may be more readable than moving the Order By clause before the Select clause.

Tomas Petricek
Do you know whether what method is more efficient on an IQueryable (Linq to SQL or as in this case Linq to Nhibernate?
Obalix
I don't have any large practical experience with both of them, so I don't know. However I would suppose that Linq to SQL could be a bit more efficient, because there is maybe smaller number of abstractions involved. But I don't think it will be a large difference.
Tomas Petricek
Thanks, I'll give it a go. will be interesting to see what sql gets sent to SQL server, which will hopefully answer the above. I'll post back here..
Simon Thompson