简体   繁体   English

带有子查询,分组依据和具有的LINQ

[英]LINQ with Sub Query, Group By, and Having

Ok, 好,

I haven't spent much time with LINQ and I'm trying to write a query in C# to replace a select statement with a sub-query, group by and having. 我没有花很多时间在LINQ上,我试图用C#编写查询,以将选择语句替换为子查询,并按组进行替换。 Here is the original query: 这是原始查询:

SELECT * FROM "Users" u1
WHERE u1.Name IN (
    SELECT u2.Name
    From "Users" u2
    WHERE Deleted IS NULL
    Group By u2.Name
    Having Count(UserName) > 1)     
ORDER BY "Name"

I can get the sub-query written like this: 我可以将子查询写成这样:

            var query = 
                from u2 in db.Users
                group u2 by u2.Name into u2g
                where u2g.Count() > 1
                select u2g.Key;

But I'm struggling to make that the sub-query and get the complete list of users with duplicate names. 但是我正在努力使该子查询并获得具有重复名称的用户的完整列表。

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks 谢谢

dbl dbl

The group itself contains the users with duplicate names - you're selecting the wrong thing. 该组本身包含具有重复名称的用户-您选择的是错误的东西。

var dupeUsers = from user in users
                group user by user.Name into dupeNames
                where dupeNames.Count() > 1
                from userDupe in dupeNames
                orderby userDupe.Name
                select userDupe;

or, in method syntax 或者,在方法语法中

var dupeUsers = users.GroupBy(user => user.Name)
                     .Where(dupeNames => dupeNames.Count() > 1)
                     .SelectMany(user => user)
                     .OrderBy(user => user.Name);

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

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