LINQ Query for Counting by Category / Subcategory

I have a table generated from a LINQ query on a datatable that has a 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 that I use to create this table is as follows:

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 the amount of each pair of categories / subcategories. for example 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  

?

+3
2

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

, (, "Glam Rock" .., , ), 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()
                        };

, "Rap Rock" "Rap" "Rock".

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

Source: https://habr.com/ru/post/1793542/


All Articles