LINQ Having Clause and Group By with condition

Hi,

While querying with LINQ, some times we will have to use the group By clause. But many a times we also want to use the having clause of SQL with the group by clause in the LINQ. There is no direct having keyword in LINQ to do this we need to use the where clause itself.

You can query the LINQ to SQL to have both Group By and Having like this.

var categories =   from p in db.Products
               group p by p.CategoryID into g
               where g.Count() >= 10
               select new {
                      g.Key,
                      ProductCount = g.Count()
                     };

But there are occasion when you might not to group with an existing column but with a column which calculated at the run time itself. For those conditions you can write the query like this.

var categories =   from p in db.Products
 
                          group p by new { Criterion = p.UnitPrice > 10 } into g
                           where g.Count() >= 10
                           select new {
                                    g.Key,
                                    ProductCount = g.Count()
                                   };

Vikram

No Comments