按列列出<t>列,按多列列出</t>

时间:2014-08-12 11:54:19

标签: c# linq linq-to-sql lambda

我正在尝试在列表上按列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)FROM YOUR_TABLE GROUP BY说明

regards

2 个答案:

答案 0 :(得分:1)

你可以尝试这个:

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) 
                                });

答案 1 :(得分:1)

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()
});