Linq Subquery with Group by

时间:2015-09-29 13:55:32

标签: linq

我有以下查询可以正常工作:

 var results = (from p in db.globalMap
                               where p.LId == 1
                               group p by p.GroupId into g
                               select new
                               {
                                   GroupId = g.Key,
                                   client = g.Select(k => k.ClientId).FirstOrDefault(),                                       
                                   cnt = g.Count()
                               }).ToList();

我想要做的是查询另一个表以获取基于ClientId的客户端名称。

我尝试了类似的东西,但得到了红色的swiggly线条。想知道如何像我想要的那样做一个子查询。

     var results = (from p in db.globalMap
                               where p.LId == 1
                               group p by p.GroupId into g
                               select new
                               {
                                   GroupId = g.Key,
                                   clientName =  (select x in db.client where x.clientId = clientId select x.clientName).FirstOrDefault(),                                       
                                   cnt = g.Count()
                               }).ToList();

1 个答案:

答案 0 :(得分:0)

你可以类似地做到第一个: -

var results = (from p in db.globalMap
               where p.LId == 1
               group p by p.GroupId into g
               select new
               {
                   GroupId = g.Key,
                   clientName =  db.client.Where(x => x.clientId == clientId)
                                          .Select(x => x.clientName).FirstOrDefault(),
                   cnt = g.Count()
               }).ToList();