[英]Group List<T> by Column and a count on multiple columns
我正在嘗試對1列列表進行GroupBy,然后對多列進行計數? 因此,下面的代碼應在如下表中顯示結果:
Category Parent Child
Test1 1 1
Test2 1
Test3 3 1
Test4 1
我在下面嘗試過此方法,但在下面仍然會得到錯誤的結果。
var categories = GetCategories()
.GroupBy(x => new{ x.Description })
.Select(group => new{ Categories = group.Key, ParentCount = group.Count(),
ChildCount = group.Select (s => s.ChildCount).Count()});
Category Parent Child
Test1 1 1
Test2 1 1
Test3 3 3
Test4 1 1
public List<Category> GetCategories()
{
List<Category> CategoryList = new List<Category>();
CategoryList.Add(new Category{
ParentCount =101,
ChildCount = 101,
Description = "Test1"
});
CategoryList.Add(new Category{
ParentCount =102,
ChildCount = null,
Description = "Test2"
});
CategoryList.Add(new Category{
ParentCount =103,
ChildCount = 103,
Description = "Test3"
});
CategoryList.Add(new Category{
ParentCount =103,
ChildCount = null,
Description = "Test3"
});
CategoryList.Add(new Category{
ParentCount =103,
ChildCount = null,
Description = "Test3"
});
CategoryList.Add(new Category{
ParentCount =null,
ChildCount = 104,
Description = "Test4"
});
return CategoryList;
}
public class Category
{
public string Description{get;set;}
public int? ParentCount{get;set;}
public int? ChildCount{get;set;}
}
我知道這在SQL中相當容易做到。
SELECT說明,COUNT(ParentCount),COUNT(ChildCount)來自YOUR_TABLE GROUP BY說明
regards
您可以嘗試以下方法:
var categories = GetCategories().GroupBy(x => x.Description)
.Select(group => new {
Categories = group.Key,
ParentCount = group.Count(x => x.ParentCount!=null),
ChildCount = group.Count(x => x.ChildCount!=null)
});
替換Select
用Where
var categories = GetCategories()
.GroupBy(x => new { x.Description })
.Select(group => new
{
Categories = group.Key,
ParentCount = group.Count(s=>s.ParentCount.HasValue),
ChildCount = group.Where(s => s.ChildCount.HasValue).Count()
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.