How to combine Where clause and group in LINQ

Can someone help me convert the code below to LINQ?

Select Catg,Count(*) From Mycatg where IsPublic=1 or FirstName='XXX' Group By Catg . 
+12
linq
source share
1 answer

In C #, something like:

 var query = from category in mycatg where category.IsPublic == 1 || category.FirstName == "XXX" group 1 by category.Catg into grouped select new { Catg = grouped.Key, Count = grouped.Count() }; 

Projection "1" makes it clear that all we need is a grouping key and a counter - individual entries in each group do not matter.

Using lambda syntax and dot notation:

 var query = mycatg.Where(category => category.IsPublic == 1 || category.FirstName == "XXX") .GroupBy(category => category.Catg, category => 1) .Select(grouped => new { Catg = grouped.Key, Count = grouped.Count() }); 
+24
source share

All Articles