简体   繁体   English

如何在 C# 中使用 lambda 或 LINQ 执行子查询、分组和聚合

[英]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. 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我们如何使用 Lambda 或可能是 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下面是 model 表示

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:使用我的SQL 到 LINQ 食谱,这是我对您的 SQL 查询的翻译:

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
          };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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