左外连接 - LINQ到数据表

时间:2013-06-19 20:56:34

标签: c# linq linq-to-dataset

我正在尝试在两个数据表上使用LINQ应用左外连接。当我尝试调试和查看结果变量中包含的数据时,我收到了下面列出的异常:

  

System.ArgumentException:值不能为null。参数名称:行

代码:

private DataTable DataTable1()
{
    DataRow dataRow = null;
    DataTable dt1 = new DataTable();
    dt1.Columns.Add("EmpId");
    dt1.Columns.Add("EmpName");
    dataRow = dt1.NewRow();
    dataRow["EmpId"] = "EMP001";
    dataRow["EmpName"] = "Ajaj Kumar";
    dt1.Rows.Add(dataRow);
    dataRow = dt1.NewRow();
    dataRow["EmpId"] = "EMP002";
    dataRow["EmpName"] = "Sanjay Gupta";
    dt1.Rows.Add(dataRow);
    dataRow = dt1.NewRow();
    dataRow["EmpId"] = "EMP003";
    dataRow["EmpName"] = "Ashish Charan";
    dt1.Rows.Add(dataRow);
    dt1.AcceptChanges();
    return dt1;
}

private DataTable DataTable2()
{
    DataRow dr = null;
    DataTable dt2 = new DataTable();
    dt2.Columns.Add("EmpId");
    dt2.Columns.Add("Salary");
    dr = dt2.NewRow();
    dr["EmpId"] = "EMP001";
    dr["Salary"] = "50000";
    dt2.Rows.Add(dr);
    dr = dt2.NewRow();
    dr["EmpId"] = "EMP002";
    dr["Salary"] = "45000";
    dt2.Rows.Add(dr);
    dt2.AcceptChanges();
    return dt2;
}

private void Form1_Load(object sender, EventArgs e)
{
    var empInfo = DataTable1().AsEnumerable();
    var empSal = DataTable2().AsEnumerable();

    var result = from dtEmpRow in empInfo
            join dtEmpSal in empSal
            on dtEmpRow.Field<string>("EmpId") equals dtEmpSal.Field<string>("EmpId")
            into outer
            from dtEmpSal in outer.DefaultIfEmpty()
            select new
            {
                Id = dtEmpRow.Field<string>("EmpId"),
                Name = dtEmpRow.Field<string>("EmpName"),
                Salary = ((dtEmpRow == null) ? "(no salary)" : dtEmpSal.Field<string>("Salary"))
            };
}

1 个答案:

答案 0 :(得分:8)

这是因为dtEmpSal为空(如果序列为空则为默认情况):

from dtEmpSal in outer.DefaultIfEmpty() // dtEmpSal is null

如果您尝试在Field<T>上呼叫DataRow分机号为null,则会出现该异常:

dtEmpSal.Field<string>("Salary") // System.ArgumentException

使用三元运算符修复它。你在附近,但检查了错误的值:

from dtEmpRow in empInfo
join dtEmpSal in empSal
    on dtEmpRow.Field<string>("EmpId") equals dtEmpSal.Field<string>("EmpId")
into outer
from dtEmpSal in outer.DefaultIfEmpty()
select new
{
    Id = dtEmpRow.Field<string>("EmpId"),
    Name = dtEmpRow.Field<string>("EmpName"),
    // here instead of dtEmpRow you should check dtEmpSal
    Salary = (dtEmpSal == null) ? "(no salary)" : dtEmpSal.Field<string>("Salary")
};