SQL conversion containing top, count, group and order to LINQ (2 objects)

Some LINQ queries will still puzzle me.

for the Hits table containing two columns, “Page” and “Date”, I want to find most pages with the most rows in a specific time fragment.

In SQL, I would use this:

SELECT TOP 10
      [Page]
      ,COUNT([Page]) as Number
FROM dbo.[Hits]
WHERE [Date] >= CONVERT(datetime,'14 Jan 2009')
AND [Date] < CONVERT(datetime,'15 Jan 2009')
Group BY [Page]
Order by Number DESC

In LINQ, I have no idea how to approach this, can someone help me here? I tried to convert it using linqer, but it just shows an error for this expression.

+5
source share
2 answers

Something like this should work:

(from p in DataContext.Hits
where (p.Date >= minDate) && (p.Date < maxDate)
group p by p.Page into g
select new { Page = g.Key, Number = g.Count() }).OrderByDescending(x => x.Number).Take(10);
+7
source
var top10hits = objectContext.Hits
  .Where(h => minDate <= h.Date && h.Date < maxDate)
  .GroupBy(h => h.Page)
  .Select(g => new { Page = g.Key, Number = g.Count() })
  .OrderByDescending(x => x.Number)
  .Take(10);
+7
source

All Articles