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

时间:2014-10-22 20:04:17

标签: c# linq group-by subquery having

确定,

我没有花太多时间在LINQ上,我试图在C#中编写一个查询,用一个子查询替换一个select语句,group by和having。这是原始查询:

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"

我可以像这样编写子查询:

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

但是我正在努力使这个子查询成为可能,并获得具有重复名称的完整用户列表。

任何帮助都将不胜感激。

由于

DBL

1 个答案:

答案 0 :(得分:3)

该群组本身包含名称重复的用户 - 您选择了错误的内容。

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;

或者,在方法语法

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