Lucky
Lucky

Reputation: 37

How to treat null value in Linq Select

fill error

Specified cast is not valid

if using :

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

fill error

Object reference not set to an instance of an object

if using the following code to get 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")
              };

Upvotes: 3

Views: 8339

Answers (2)

Dean Chalk
Dean Chalk

Reputation: 20471

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

firstly, you can replace Convert.ToDouble("0") to 0d

secondly you are not checking for null as in your previous line (gaia != null) ?

is this the problem ?

Upvotes: 2

RameshVel
RameshVel

Reputation: 65877

You can use Convert.DBNull

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

Upvotes: 1

Related Questions