2009-02-16 128 views
1

我有兩個表,產品和類別。我如何將以下sql查詢轉換爲linq格式?將ms sql「group by」查詢轉換爲linq to sql

select c.Name, c.DisplayName, count(p.id) from categories as c 
LEFT join products as p on p.categoryId = c.id 
group by c.Name, c.DisplayName 

一些類別將有0的產品裏面,這樣LEFT JOIN,如果你正確地定義模型中的關係,則客戶表應與所有產品關聯,所以你很重要

回答

2

」只需使用'c.Products'即可訪問與客戶相關的產品。那麼應該能夠簡單地寫是這樣的:

var q = 
    from c in categories 
    select new { c.Name, c.DisplayName, Count = c.Products.Count() } 

T.

+0

wow linq給我留下了深刻的印象,每天都有更多。謝謝你的答案! – jorsh1 2009-02-16 20:51:07

0
dc.categories 
.Select(c => new 
{ 
    Name = c.Name, 
    DisplayName = c.DisplayName, 
    TheCount = c.Products.Count() 
} 

如果你想要做一個左在其他情況下加入,檢查出「集團加入」。

dc.categories 
.GroupJoin(dc.products, 
    c => c.id, 
    p => p.categoryid, 
    (c, g) => new { Name = c.Name, TheCount = g.Count() } 
); 
0

在基礎上顯示分組。

var q = from c in db.categories 
    group c by new {c.Name , c.DisplayName} into alias 
    select new { alias.Name, 
       alias.DisplayName, 
       Count = alias.Count(p => p.id) 
       }