如何在Linq Select中处理空值

时间:2010-11-24 10:17:17

标签: c# linq

填写错误

  

指定的演员表无效

如果使用:

annual_leave_balance = (gaia == null) ? Convert.ToDouble("0") : gaia.Field<double?>("Annual Leave Balance"),

填写错误

  

对象引用未设置为对象的实例

如果使用以下代码获得年假余额:

annual_leave_balance = (gaia["Annual Leave Balance"] == null) ? Convert.ToDouble("0") : gaia.Field<double>("Annual Leave Balance"),

var results = from bird in mssql_dataTable.AsEnumerable()
              join lion in dataTable.AsEnumerable() on bird.Field<Int32>("ExternalID") equals Convert.ToInt32(lion.Field<double>("External ID"))
              join gaia in Kiosk_mssql_dataTable.AsEnumerable() on bird.Field<Int32>("EmployeeID") equals Convert.ToInt32(gaia.Field<string>("StaffID"))
              into joinKioskEmp
              from gaia in joinKioskEmp.DefaultIfEmpty()
              select new
              {
                  employee_id = bird.Field<Int32>("EmployeeID"),
                  payrollnum = bird.Field<string>("PayrollNum"),
                  employee_name = (gaia != null) ? (gaia.Field<string>("First Name")+", "+gaia.Field<string>("Last Name")) : ((bird != null) ? (bird.Field<string>("FirstName")+", "+bird.Field<string>("Surname")) : ""),
                  //employee_name = (gaia != null) ? (gaia.Field<string>("First Name") + ", " + gaia.Field<string>("Last Name")) : "",
                  annual_leave_balance = (gaia["Annual Leave Balance"] == null) ? Convert.ToDouble("0") : gaia.Field<double>("Annual Leave Balance"),
                  _position = bird.Field<string>("position"),
                  external_id = bird.Field<Int32>("ExternalID"),
                  approver = lion.Field<string>("Approver"),
                  approver_email = lion.Field<string>("Approver Email Address")
              };

2 个答案:

答案 0 :(得分:2)

annual_leave_balance = (gaia["Annual Leave Balance"] == null) 
      ? Convert.ToDouble("0") : gaia.Field<double>("Annual Leave Balance")

首先,您可以将Convert.ToDouble("0")替换为0d

其次,您没有检查上一行(gaia != null) ?

中的null

这是问题吗?

答案 1 :(得分:1)

您可以使用Convert.DBNull

 annual_leave_balance = (gaia["Annual Leave Balance"] == Convert.DBNull) ? Convert.ToDouble("0") : gaia.Field<double>("Annual Leave Balance"),