2010-05-04 84 views
8

我有2個表格,論壇和帖子。
我想檢索所有論壇字段與一個新的額外字段:計數屬於此論壇的所有帖子。Linq加入COUNT

我有這個現在:

var v =(from forum in Forums 
    join post in Posts on forum.ForumID equals post.Forum.ForumID 
    select new 
    { 
     forum, //Need to retrieve all fields/columns from forum  
     PostCount = //count all post that belong to this forum with a condition: count it only if post.Showit==1 

    } 
    ).Distinct() 
  1. 的加入必須LEFT JOIN:如果沒有職位屬於一些論壇,論壇的字段應被檢索但PostCount場應爲0。
  2. 結果集必須是不同的(加盟給我的全交叉...或者它怎麼叫)
+0

任何人都知道,如果我可以在SQL服務器上做些什麼來優化這些查詢?我有同樣的情況,但需要多個Count()結果 – 2010-05-04 22:44:19

回答

16

我想你想要的東西,如:

from forum in Forums 
// ForumID part removed from both sides: LINQ should do that for you. 
// Added "into postsInForum" to get a group join 
join post in Posts on forum equals post.Forum into postsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = postsInForum.Where(post => post.ShowIt == 1).Count() 
} 

或(在評論中指出),你可以把一個條件在Count電話 - 我總是忘記的可用:)

from forum in Forums 
// ForumID part removed from both sides: LINQ should do that for you. 
// Added "into postsInForum" to get a group join 
join post in Posts on forum equals post.Forum into postsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = postsInForum.Count(post => post.ShowIt == 1) 
} 

「顯示」爲唯一的過濾另一種選擇職位將要做到這一點的加入:

from forum in Forums 
join post in Posts.Where(post => post.ShowIt == 1) 
    on forum equals post.Forum into shownPostsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = shownPostsInForum.Count() 
} 

我相信,所有的這些都邏輯正確的,但我不知道SQL將是什麼樣子?

+0

難道你不能'PostCount = g.Count(post => post.ShowIt == 1)'?或者僅用於LinqToObject? – ANeves 2010-05-04 16:44:57

+0

@sr pt:是的,好點。將編輯:) – 2010-05-04 16:45:26

+0

你能否請求解釋單詞「進入」它的使用;不應該用於「組」? – shivesh 2010-05-04 16:49:00

2

如果您將論壇連接到linqtosql設計器中的帖子,這將創建可查詢的關係屬性。

var query = 
    from f in db.Forums 
    select new 
    { 
    forum = f, 
    PostCount = f.Posts.Count(p => p.ShowIt == 1) 
    };