[英]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.