5

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

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

代码:

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"))
            };
}
4

1 回答 1

8

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

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

当您尝试调用为 null 的Field<T>分机时DataRow,您会收到该异常:

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")
};
于 2013-06-19T21:00:55.983 回答