Tuesday, May 3, 2011

How to combine Where clause and group by in LINQ

Hi All, I am learning LINQ and got stuck here :-(. Can any one help me converting below code to LINQ?

Select Catg,Count(*)  From Mycatg  where IsPublic=1 or FirstName='XXX' Group By Catg  .
From stackoverflow
  • 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() };
    

    The projection of "1" makes it clear that all we need is the key of the grouping and the count - the individual entries in each grouping are irrelevant.

    EDIT: Now with 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() });
    
    Cloud : You are so fast when it comes to LINQ. Nice example!
    Jose Basilio : @Jon - For extra credit, can you do this same query in lambda syntax?
    Wondering : Thanks Jon for ur help

0 comments:

Post a Comment