Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use group by and having count in Linq

Tags:

c#

linq

I am having trouble trying to convert the following query from SQL to Linq, in particular with the having count and group by parts of the query:

select ProjectID
from ProjectAssociation

where TeamID in ( select TeamID 
                  from [User]
                  where UserID in (4))
group by ProjectID
having COUNT(TeamID) = (select distinct COUNT(TeamID)
                        from [User]
                        where UserID in (4))

Any advice on how to do so would be much appreciated.

like image 399
Luke Avatar asked Apr 04 '10 19:04

Luke


People also ask

How can we do a GroupBy using LINQ query?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.

How do you count in LINQ?

In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.

How do I group count in C#?

EMP. GroupBy(p => p. departmentname) select new { count = p. Count(), p.

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want: DataTable tempData = (DataTable)grdUsageRecords.


2 Answers

var groups = from pa in ProjectAssociation let teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID) where teamIds.Contains(pa.TeamID) group pa by pa.ProjectID;

var result = from g in groups
   let count = User.Where(u => u.UserID == 4).Select(u => u.TeamID).Distinct().Count()
   where g.Count() == count
   select g.Key;

Or maybe more optimal:

var teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID).AsEnumerable();
var groups = ProjectAssociation.Where(pa => teamIds.Contains(pa.TeamID)
   .GroupBy(pa => pa.ProjectID);
var result = from g in groups
       let count = teamIds.Distinct().Count()
       where g.Count() == count
       select g.Key;

By the way, i think that by

select distinct COUNT(TeamID)

you meant:

select COUNT(distinct TeamID)
like image 100
ILya Avatar answered Sep 22 '22 19:09

ILya


There is a tool (cheap) that will convert queries like this for you. It's called Linqer. I own a copy and have found that it's able to convert event the most complex of queries. The URL is http://www.sqltolinq.com/

It's not free, but it's pretty inexpensive and has a 30 day trial.

like image 44
Randy Minder Avatar answered Sep 22 '22 19:09

Randy Minder