开发者

LINQ Query to count by distinct category / subcategory

I have a table, generated from a LINQ query on a datatable, which has subcategory and category fields:

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  

The LINQ query I am using to generate this table is:

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

Now I want to get a count of each category/subcategory pair. e.g. for the above example I want to return:

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

How can I acheive this?


Try:

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

If you want to enforce that subcategories always have the same parent category (given that the sub-categories are named "Glam Rock" etc., I assume that this is in fact the case), do:

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

This will throw an exception if "Rap Rock" turns up as a subcategory of both "Rap" and "Rock".


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜