简体   繁体   中英

How to perform subquery,group by and aggregate together using lambda or LINQ in C#

I'm trying to perform groupby with aggregate function inside a subquery using lambda expression.I've manage to write the query using SQL but failing to do the same using Lambda expression. How could we write the same query using Lambda or may be LINQ

select 
  [user_ID], FirstName, LastName, Phone, Fax, EmailAddress 
from table1  
where [user_id] in 
    (select [user_id] 
     from table2 group by [USER_ID]  
     having (sum(case when isregistered is not null then 1 else 0 end)) = 0
    )

Below is the model representation

public class AccountDetails
{
    public string Username { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
    public string EmailAddress { get; set; }
    public bool? IsRegistered { get; set; }
    public string User_Id { get; set; } 
}

Using my SQL to LINQ Recipe , here is my translation of your SQL query:

var subq = from a in table2
           group a by a.User_Id into ag
           where ag.Sum(a => a.IsRegistered != null ? 1 : 0) == 0
           select ag.Key;

var ans = from a in table1
          where subq.Contains(a.User_Id)
          select new {
              a.User_Id,
              a.FirstName,
              a.LastName,
              a.Phone,
              a.Fax,
              a.EmailAddress
          };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM