Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine Where clause and group by in LINQ

Tags:

linq

Can any one help me convert the below code to LINQ?

Select Catg,Count(*)  From Mycatg  where IsPublic=1 or FirstName='XXX' Group By Catg  .
like image 796
Wondering Avatar asked Apr 29 '09 13:04

Wondering


People also ask

Can we use multiple where clause in LINQ?

Filter collections using Where clause in C#. A single query expression may have multiple where clauses.

Can we use joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables.

What is where clause in LINQ?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.

How does GroupBy work in LINQ?

GroupBy allows you to quickly group collections of related data by specific properties on your data. The grouped data is then arranged by sub-collections of items in those groups. Note: LINQ provides variants of each method in this article that work with either IEnumerable or IQueryable .


1 Answers

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.

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() });
like image 183
Jon Skeet Avatar answered Sep 26 '22 07:09

Jon Skeet