结合linq查询

时间:2009-12-08 11:12:53

标签: .net linq-to-sql join

我有几个linq查询,我想加入

var IDs = from p in ctx.bam_Zending_AllInstances
                          where p.Zender == "RT30"
                          select new { Identificatie = p.Identificatie };

                var latestIDs = from p in ctx.bam_Zending_AllInstances
                                where p.Zender == "RT30"
                                group p by p.Identificatie into q
                                select new { Identificatie = q.Key, Datum = q.Max(p => p.PrestatieOntvangen) };

                var final = from p in IDs
                            join q in latestIDs on p.Identificatie equals q.Identificatie
                            select new { Identificatie = p.Identificatie };

问题是。如果我查看结果,ID有308项,最新ID有304项,但最后一项也有308项。这怎么可能?我认为linq的加入是内部联接。我需要有304个项目,但它确实是一个外部联接。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您确定此处有唯一ID吗?如果您有两个具有相同ID的行,则该连接将生成四个匹配而不是两个。

我建议您查看最终查询生成的SQL - 我当然希望它是内部联接。

答案 1 :(得分:0)

ID确实不是唯一的。

我通过使用两个条件来解决问题:

var IDs = from p in ctx.bam_Zending_AllInstances
                          where p.Zender == "RT30"
                          select new { ID = p.Identificatie, Datum = p.PrestatieOntvangen };

                var latestIDs = from p in ctx.bam_Zending_AllInstances
                                group p by p.Identificatie into q
                                select new { ID = q.Key, Datum = q.Max(p => p.PrestatieOntvangen) };

                var final = from p in IDs
                            join q in latestIDs on new { p.ID, p.Datum } equals new { q.ID, q.Datum }
                            select new { ID = p.ID };
相关问题