Lambda LINQ查询有问题

时间:2015-09-15 23:56:04

标签: c# .net linq lambda

我试图将以下SQL表达式转换为Lambda LINQ查询,而我现在似乎要绕圈子了:

select m.MemberExternalPK FROM Member.Member AS m INNER JOIN Member.Account AS a ON m.MemberID = a.MemberID where m.MemberExternalPK in 
(
    SELECT m.MemberExternalPK
    FROM Member.Member AS m INNER JOIN Member.Account AS a ON m.MemberID = a.MemberID
    group by MemberExternalPK
    having Count(AccountID) = 1 
)
and AccountStatusID = 3

到目前为止,我已设法获得以下语法,该语法将返回正确的行数,但是所有列(除了我想要的MemberExternalPK)!

Members.Join(Accounts, m => m.MemberID, a => a.MemberID, (m, a) => new { m, a })
    .GroupBy(t => t.m.MemberExternalPK, t => t.a)
    .Where(grp => grp.Count(p => p.AccountID != null) == 1)
    .SelectMany(sublist => sublist).Where(x => x.AccountStatusID == 3)

2 个答案:

答案 0 :(得分:0)

我认为这非常接近:

var query =
    from m in Member_Member
    join a in Member_Account on m.MemberID equals a.MemberID
    group a by m.MemberExternalPK into gas
    where gas.Count(ga => ga.AccountID != null) == 1
    from ga in gas
    where ga.AccountStatusID == 3
    select gas.Key;

唯一关注的是ga.AccountID != null,这意味着gas群组可能有多条记录,因此最终可能会有多个gas.Key

答案 1 :(得分:0)

这样的东西?拆分它也可以提高性能。

var externalMembers = 
    Members.Join(Accounts, m => m.MemberID, a => a.MemberID, (m, a) => new { m, a })
           .GroupBy(grp => grp.MemberExternalPK)
           .Where(grp => grp.Count() > 1)
           .Select(grp => grp.Key);

var result = 
    Members.Where(w => externalMembers.Contains(w.MemberExternalPK) && w.AccountStatusID == 3)
           .Select(s => s.MemberExternalPK)