在linq中使用group by到sql

时间:2016-11-11 14:34:12

标签: c# linq linq-to-sql

我在组中有一个问题,链接到sql
首先我有这个表:

  1. 客户:Id_client,nom,prenom,villeId
  2. ville :id_ville,nom
  3. 代码:

     justiceDataContext dbContext = new justiceDataContext();
            GridView1.DataSource = from client in dbContext.Client
                                   join ville in dbContext.Commande
                                   on client.villeId equals ville.Id_ville
                                   group client by ville.nom into g
                                   select new { City = g.Key, NumberOfClients = g.Count() };
            GridView1.DataBind();
    

    我的目标是按城市(client

    获取ville的数量

    谢谢

1 个答案:

答案 0 :(得分:0)

dbContext.Client
    .GroupBy(c => c.villeId)
    .Select(g => new {
        CityName = dbContext.Villes.Where(v => v.Id_ville == g.Key),
        NumberOfClient = g.Count()
    }).ToList();

另一种方法:

var result = dbContext.Villes
            .Join(dbContextClients, v => v.IdVille, c => c.IdVille, (v, c)  => new { client = c, ville = v })
            .GroupBy(j => j.ville.IdVille)
            .Select(g => new {
                VilleName = g.First().ville.Name,
                NumberOfClients = g.Count()
            }).ToList();