Linq to SQL with group by

时间:2009-12-30 23:11:54

标签: sql vb.net linq linq-to-sql linq-group

如何在linq VB.NET中编写此查询?

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个相同对象的数组

依此类推......我该如何每行只返回一个对象?

1 个答案:

答案 0 :(得分: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);