Having clause and Grouping Based on condition in LINQ

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


Share this post   Email it

Feedback

Posted on 11/22/2009 9:17:31 AM

Hi, how to write groupby with DB column..?

var Query = from objT1 in objDC.Table1
join objT2 in objDC.Table2 on objT1.ID equals objT2.ID
group objT1 by objT1.Number into x
where objT1.ImportanceID == "MANDATORY"
select new
{
objT2.Dsc
};

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia