[英]Linq Group By Multiple Columns
我是linq的新手,很難弄清楚該如何寫。
我有以下名為animalList的集合
AnimalName - MG - Hatch
An1 - 1 - 1
An1 - 1 - 2
An1 - 1 - 3
An2 - 2 - 4
An2 - 2 - 3
我需要查看每個動物以及毫克/孵化組合的數量:
AnimalName - Count
An1 - 3
An2 - 2
對於每只動物,我需要一個不同的計數,其中MG / Hatch行具有不同的值。
這是我正在使用的查詢,但是在獲取正確計數時仍然遇到問題。
var query = (from a in animalList).ToList()
group a by new { a.AnimalName, a.MG,a.Hatch }
into grp
select new
{
grp.Key.AnimalName,
grp.Key.MG,
grp.Key.Hatch,
Quantity = grp.Count()
}).ToList();
首先,您的查詢不會編譯。 為了使其編譯,您必須進行更改
(from a in animalList).ToList()
至
(from a in animalList
除此之外group a by new { a.AnimalName, a.MG,a.Hatch }
按所有屬性對動物進行分組( group a by new { a.AnimalName, a.MG,a.Hatch }
進行分組)。 這將為AnimalName
, MG
和Hatch
每種不同組合提供一個組。 在您的情況下,沒有動物具有相同的名稱,剖面線和MG,因此列表中的所有條目都將擁有自己的組,這將導致grp.Count()
返回1。
如果我對您的理解正確,則可以使用嵌套查詢解決此問題。
像這樣:
var query = from animal in animalList
group animal by animal.AnimalName into grp
select new
{
AnimalName = grp.Key,
Quantity = (from an in grp
group an by new { an.Hatch, an.MG } into combinations
select combinations).Count()
};
外部查詢按名稱對動物進行分組,內部查詢找到Hatch
和MG
的不同組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.