2011-06-17 66 views
0

C#或VB.NET很好。LINQ to SQL計數表與關係

我想從與LINQ下表計算的人數爲每個國家到SQL

我有兩個表,一個是國家和其他人是。這是從國家到人民的一對多關係。

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

我想統計每個國家有多少人,並得到如下結果,只顯示有人的國家。 因爲有些國家在People表中沒有人。

  • 美國:10
  • 中國:20
  • 俄羅斯:15

等..

謝謝。

回答

2
(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()} 
0

那麼其一定的技巧..你必須使用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

+0

Thi s查詢不會返回想要的結果,它當然不是最簡單的方法 – Vedran 2011-06-17 08:09:20

+0

我測試過了! – casper123 2011-06-17 12:20:59