需要有关LINQ查询左连接和多个字段的帮助

时间:2010-11-12 07:10:45

标签: c# sql linq linq-to-sql c#-4.0

我有以下SQL查询,我想重写为LINQ:

SELECT gp.Name
 , r.DateOfRace
 , ISNULL(SUM(rr.Points), 0) AS Points
FROM Races r
INNER JOIN GrandPrix gp
 ON r.GrandPrixId = gp.GrandPrixId
LEFT JOIN Predictions p
 ON p.RaceId = r.RaceId
 AND p.AdditionalUserInformationId = 2
LEFT JOIN RaceResults rr
 ON p.DriverId = rr.DriverId
 AND p.FinishPosition = rr.FinishPosition
 AND p.RaceId = rr.RaceId
WHERE r.Season = 2010
GROUP BY gp.Name
 , p.RaceId
 , r.DateOfRace

这是我得到的,当它仍在工作时:

from races in Races
join grandprix in GrandPrixes
on races.GrandPrixId equals grandprix.GrandPrixId
from Predictions in Predictions.Where(v => v.RaceId == races.RaceId).DefaultIfEmpty()
select new
{
 DateOfRace = races.DateOfRace,
 GrandPrix = grandprix.Name,
}

当我走得更远时,事情就出错了 - 我不能让AND p.AdditionalUserInformationId = 2正确。

我希望有人可以提供帮助!

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

join p in Predictions
    on new { p.RaceId, p.AdditionalUserInformationId } =
       new { r.RaceId, AdditionalUserInformationId = 2 } into ps
from p in ps.DefaultIfEmpty()
join rr in RaceResults
    on new { p.DriverId, p.RaceId, p.FinishPosition } =
       new { rr.DriverId, rr.RaceId, rr.FinishPosition } into rrs
from rr in rrs.DefaultIfEmpty()

您可以使用C#的功能在结构上比较匿名类型。使用相同的属性创建两个匿名类型,这使它们成为同一个类的实例。然后可以比较这些实例。

答案 1 :(得分:1)

join grandprix in GrandPrixes
on new {races.GrandPrixId, p.AdditionalUserInformationId} equals new {grandprix.GrandPrixId,2}