2016-08-23 34 views
1

其他相關表格請幫我完成以下查詢:LINQ GROUP BY查詢的幫助:選擇鍵

var results = from species in db.Species 
       join cats in db.Categories on species.CategoryId equals cats.CategoryId 
       join groups in db.Groups on cats.GroupId equals groups.GroupId 
       group groups by groups into g 
       select new GroupWithCategoryChildren 
       { 
        Group = g.Key, 
        Categories = (cats from above query for this same g.Key group)??? 
       }; 

我可以用SQL做到這一點真的很容易,但我與LINQ掙扎。我想結束每個Group的列表,並在上面的/主要單個查詢中加入cats,理想情況下不需要在單獨的查詢中重新查詢該數據。

非常感謝

+2

你能後你會怎麼做,在SQL?這將告訴我們你需要什麼,而LINQ專家可以很容易地爲你翻譯。 –

+0

您可以在LINQ中使用子查詢,但正如香農所提到的,沒有看到您的SQL或所有這些表應該如何相互關聯,都無法回答您的問題。 – Connor

+0

對不起,我意識到我沒有提供原始問題中的最佳解釋。 – Aaron

回答

1

我不知道我理解正確的,但我覺得這是你所需要的:與其group groups by groupsgroup cats by groups然後Key將是groups和組的值將是所有匹配的類別。

var results = from species in db.Species 
       join cats in db.Categories on species.CategoryId equals cats.CategoryId 
       join groups in db.Groups on cats.GroupId equals groups.GroupId 
       group cats by groups into g 
       select new GroupWithCategoryChildren 
       { 
        Group = g.Key, 
        Categories = g.ToList() 
       }; 

我用這個來測試它:

List<dynamic> Species = new List<dynamic>() 
{ 
    new { A = "1", CategoryId = 1 }, 
    new { A = "2", CategoryId = 2 }, 
}; 

List<dynamic> Categories = new List<dynamic> 
{ 
    new { B = "1", CategoryId = 1, GroupId = 1 }, 
    new { B = "2", CategoryId = 2, GroupId = 1 }, 
}; 

List<dynamic> Groups = new List<dynamic> 
{ 
    new { C = "1", GroupId = 1 } 
}; 

//result: { Group: { C = "1", GroupId = 1 }, Categories (1,2)} 
+0

@Aaron - 這有助於你解決問題嗎? –

+0

嗨吉拉德,非常感謝。是的,這正是我所需要的。我最終實現了這個稍微變化的版本(因爲我還需要深入到另一個二級),但它基於上面顯示的示例解決方案。非常感謝您的幫助。 – Aaron

+0

@Aaron - 歡迎您:) –