tags:

views:

1003

answers:

2

Some LINQ queries still puzzle me.

for a table 'Hits' containing two columns, 'Page' and 'Date', I want to find the most Pages with the most rows in a defined slice of time.

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 got no idea how to approach this, can anyone help me here? I tried to convert it using linqer, but it just shows an error for this expression.

+5  A: 

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);
veggerby
Typo in p < maxDate -> p.Date < maxDate :)
Sam
Sam
+4  A: 
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);
David B
Typo in .Select(g => Page = g.Key, Number = g.Count()}) -->.Select(g => new {Page = g.Key, Number = g.Count()})Otherwise "same same.. but different" :)
veggerby
Thanks for the typo notice - veggerby; and the edit - Justice.
David B
Also - @"same same... but different" I find the extension methods are more discoverable than the query comprehension syntax. So that's what I use.
David B