0

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
AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
Simon Thompson
  • 708
  • 6
  • 14

1 Answers1

1

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
  • 240,744
  • 19
  • 378
  • 553
  • Do you know whether what method is more efficient on an IQueryable (Linq to SQL or as in this case Linq to Nhibernate? – AxelEckenberger Mar 24 '10 at 19:59
  • 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 Mar 24 '10 at 20:50
  • 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 Mar 24 '10 at 22:02