LINQ查询按不同的类别/子类别计数

时间:2011-02-21 09:16:48

标签: c# linq datatable

我有一个表,是从数据表上的LINQ查询生成的,它有子类别和类别字段:

Name...........Category.........Subcategory  
Kiss...........Rock.............Glam Rock  
Metallica......Rock.............Hard Rock  
Bon Jovi.......Rock.............Soft Rock  
Slade..........Rock.............Glam Rock  
Meatloaf.......Rock.............Soft Rock  
Wilee..........Dance............Grime  
Mgmt...........Dance............Nu Rave  
Dizee..........Dance............Grime  

我用来生成此表的LINQ查询是:

var qCategory = from c in dtCategory.AsEnumerable()
            select new {
                Artist = c.Field<string>("Artist"),
                Category = c.Field<string>("Category"),
                Subcategory = c.Field<string>("Subcategory")
             };

现在我想得到每个类别/子类别对的计数。例如对于上面的例子,我想返回:

Category............Subcategory.......Count  
Rock................Glam Rock.........2  
Rock................Soft  Rock........2   
Rock................Hard Rock.........1  
Dance...............Grime.............2  
Dance...............Nu Rave...........1  

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:4)

尝试:

var counts = from artist in qCategory
             group artist by new { artist.Category, artist.Subcategory } 
                          into g
             select new { 
                           g.Key.Category,
                           g.Key.Subcategory, 
                           Count = g.Count() 
                        };

如果你想强制执行那些子类别总是有相同的父类别(假设子类别被命名为“Glam Rock”等,我认为事实上就是这样),做:

var counts = from artist in qCategory
             group artist by artist.Subcategory into g
             select new {
                           Category = g.Select(a => a.Category)
                                       .Distinct()
                                       .Single(),
                           Subcategory = g.Key,
                           Count = g.Count()
                        };

如果“Rap Rock”成为“Rap”和“Rock”的子类别,这将引发异常。

答案 1 :(得分:2)

qCategory.
  GroupBy(item => new {Category = item.Category, Subcategory = item.Subcategory}).
  Select(group => new {Category = group.Key.Category, Subcategory = group.Key.Subcategory, Count = group.Count()})