using group by in linq to sql

本文关键字:to sql linq in group by using | 更新日期: 2023-09-27 18:17:23

我有一个问题组通过链接到sql
首先我有这些表:

  1. client: Id_client, nom, prename, villeId
  2. ville: id_ville, nom
代码:

 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();

我的目标是按城市(ville)获得client的数量

谢谢

using group by in linq to sql

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();