2013-06-19 222 views
3

我想在兩個數據表上應用使用LINQ的左外連接。當我嘗試調試和查看結果變量中包含的數據時,我收到以下異常:左外連接 - LINQ到Datatable

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

回答

7

那是因爲這裏dtEmpSal爲空(默認情況下,如果序列爲空):

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

當你正試圖在上撥打Field<T>分機號碼這是空,你會得到異常:

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

感謝您的快速回復。你的建議解決了這個問題。 –