2009-12-30 120 views
0

如何在linq VB.NET中編寫此查詢?Linq to SQL by group by

select top 15 count(1), A.Latitude, A.Longitude 
from Bairro A 
inner join Empresa B on B.BairroID = A.BairroID 
where A.CidadeID = 4810 
group by A.Latitude, A.Longitude 
order by COUNT(1) desc 

我達到了這個代碼:

Dim TopBairros = (From A In Bairros _ 
        Join B In New BO.Empresa().Select On B.BairroID Equals A.BairroID Group A By A.Latitude, A.Longitude Into g = Group _ 
        Select g Distinct _ 
        Order By g.Count Descending).Take(15) 

每行具有含有屢與計數數的同一對象陣列集合。例如:

行0:874個相同的對象 第1排陣:710個相同的對象

等的陣列......我該怎麼辦每行返回只有一個對象?

回答

3

試試這個:

var query = from a in context.Bairro 
      where a.CidadeID == 4810 
      join b in context.Empresa on a.BairroID equals b.BairroID 
      group a by new { a.Latitude, a.Longitude } into grouped 
      orderby grouped.Count() descending 
      select new { grouped.Key.Latitude, 
         grouped.Key.Longitude, 
         Count = grouped.Count() }; 
var top15 = query.Take(15); 
+0

我使用VB.NET ......我達到了這個代碼: 昏暗TopBairros =(從在Bairros _ JOIN B在新BO.Empresa()。選擇On B.BairroID Equals A.BairroID Group A按A.Latitude,A.Longitude進入g = Group _ 選擇g Distinct _ Order by g.Count Descending).Take(15) 每行都有一個數組集合重複包含與計數相同的對象。例如: 第0行:874個相同對象的數組 第1行:710個相同對象的數組 等等......如何才能每行只返回一個對象? – Fernando 2009-12-30 23:51:30

+0

@Fernando:通過使用最後得到的投影 - 選擇組的關鍵和計數。 – 2009-12-31 00:49:06