【问题标题】:LINQ to SQL count table with relationship具有关系的 LINQ to SQL 计数表
【发布时间】:2011-06-17 15:25:11
【问题描述】:

C# 或 VB.NET 都可以。

我想用 LINQ to SQL 从下表中统计每个国家/地区的人数

我有两张表,一张是国家,另一张是人。国家与人民之间是一对多的关系。

Countries table column:CountryId,CountryName
People:PeopleId,FullName,CountryId (a primary key from Country table and allowed null)

我想计算每个国家/地区有多少人,并得到类似于以下结果的结果,该结果仅显示有人口的国家/地区。 因为有些国家/地区在 People 表中没有人。

  • 美国:10
  • 中国:20
  • 俄罗斯:15

等等..

谢谢。

【问题讨论】:

    标签: c# vb.net linq linq-to-sql


    【解决方案1】:
    (from c in Countries
    select new { c.CountryName, Count = c.People.Count()}).Where(r => r.Count > 0)
    

    from c in Countries.Where(r => r.People.Any())
    select new { c.CountryName, Count = c.People.Count()}
    

    【讨论】:

      【解决方案2】:

      这有点棘手.. 你必须使用 LINQ 来使用关系,尝试使用这个查询

          var count = from pl in dc.People join ci in dc.Countries on pl.CountryId equals ci.CountryId groupby ci.CountryId select PeopleId.count();
      

      还有很多其他方法可以编写 LINQ 查询,但它是最简单的方法。有关 LINQ to SQL 的更多信息,您可以查看我的博客:LinqtoSQL

      【讨论】:

      • 这个查询不会返回想要的结果,它当然不是最简单的方法
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      相关资源
      最近更新 更多