如何在Linq中获得以下输出

时间:2014-03-28 06:33:17

标签: c# linq datatable

如何模拟此Sql查询:

Select A.FID, A.SLNO, A.Date as FromDate, A1.Date ToDate
From #Test A
Inner Join #Test A1 On A.FID = A1.FID And A1.SLNO = A.SLNO + 1

给出了:

enter image description here

使用此查询提供相同的输出:

var results2 = from table1 in dtSplitDates.AsEnumerable()
join table2 in dtSplitDates.AsEnumerable() on new { FID = table1.Field<int>("FID"), SLNO = table1.Field<int>("SLNO")} equals new { FID = table2.Field<int>("FID"), SLNO = table2.Field<int>("SLNO") }  into lj
from r in lj.DefaultIfEmpty()
select dtSplitDates2.LoadDataRow(new object[]
{
    r["FID"],
    r["SLNO"],
    r == null ? string.Empty : r["Dates"]
}, false);

我无法修改我的选择列表和加入条件 - 当我尝试获取Object reference not set to an instance of an object.时有2个表dtSplitDatesdtSplitDates2

这就是表dtSplitDates现在的样子,dtSplitDates2是它的克隆:

enter image description here

2 个答案:

答案 0 :(得分:0)

lj.DefaultIfEmpty()

将返回null而不带参数。传递一些默认值。

答案 1 :(得分:0)

什么是dtSplitDates2?

请与您分享您的餐桌内容。

但我明白,我更喜欢这个解决方案

     var results2 = from table1 in dt1.AsEnumerable()
                       join table2 in dt2.AsEnumerable() on new { FID = table1.Field<int>("FID"), SLNO = table1.Field<int>("SLNO") } equals new { FID = table2.Field<int>("FID"), SLNO = table2.Field<int>("SLNO") } into lj
                       from r in lj.DefaultIfEmpty()
                       select new
                       {
                           FID = r["FID"],
                           SLNO = r["SLNO"],
                           Dates = r == null ? string.Empty : r["Date"]
                       };