左外连接IEnumerable <t>到DataTable - 参数不能为空错误</t>

时间:2015-04-02 19:04:48

标签: c# linq

我有这个:

var initialRelease = from c in campaignAvailability
                        where c.reportStatus == "Initial Release"
                        select c;

var results = from server in initialRelease
              join local in table.AsEnumerable()
              on server.campaignId equals local.Field<long>("campaignId") into ls
              from local in ls.DefaultIfEmpty()
              where DateTime.Compare(server.reportDate, local.Field<DateTime>("reportDate")) > 0 || local == null
              select server;

//add it to list of campaigns to process
results.Select(m => new { m.campaignId, m.reportDate }).Distinct()
    .Select(n => new CampaignReportDate() {
        campaignId = n.campaignId,
        reportDate = n.reportDate
    }).ToList().ForEach(c => campaignsToProcess.Add(c));

我希望在SQL中看起来像这样:

SELECT a
FROM ienumerable AS a
LEFT OUTER JOIN table AS b
ON
    a.id = b.id
WHERE b.some_date > a.some_date
    OR b IS NULL

我了解where linq条款无法比较null日期。但是,据我所知,|| local == null应该照顾到这一点。我错过了什么?

2 个答案:

答案 0 :(得分:1)

想出来。 localnull进入,我仍然需要一种方法将其与server.reportDate进行比较。我使用了三元运算符。由于我将DateTime.MinValue指定为默认日期,因此我可以移除|| local == null

where DateTime.Compare(server.reportDate, (local != null) ? (DateTime)local["reportDate"] : DateTime.MinValue) > 0

答案 1 :(得分:0)

在linq中将对象连接到对象时,您应该更喜欢在空时提供默认值。然后您的查询不需要做太多更改。

var results =
    from server in initialRelease
    join local in table.AsEnumerable()
        on server.campaignId equals local.Field<long>("campaignId") into ls
    from local in ls.DefaultIfEmpty(table.NewRow())
    where DateTime.Compare(server.reportDate,
            local.Field<DateTime?>("reportDate") ?? Datetime.MaxValue) > 0
    select server;