sammarcow
sammarcow

Reputation: 2956

LINQ not checking for null

The following code is supposed to take a simple average of Tuition rates if present for each row, but the requirement dictates the imported data set allow null values.

The line below is not properly checking value and I am getting the error: "ArgumentNullException was unhandled by user code, Value cannot be null."

TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"),null))
    .DefaultIfEmpty()
    .Average(p => p.Field<double>("TUITION")),

Upvotes: 1

Views: 1088

Answers (2)

dlev
dlev

Reputation: 48596

You should be comparing to DBNull.Value, not null:

TUITIONCurr = g
    .Where(p => !object.Equals(p.Field<double>("TUITION"), DBNull.Value))
    .Average(p => p.Field<double>("TUITION"));

Once you've filtered out nulls, you don't need the DefaultIfEmpty() call.

Upvotes: 2

Donut
Donut

Reputation: 112795

Instead of the DataRow.Field method, try using DataRow.IsNull. Also, you don't need the call to DefaultIfEmpty().

E.g.:

TUITIONCurr = g
   .Where(p => !p.IsNull("TUITION"))
   .Average(p => p.Field<double>("TUITION")),

Upvotes: 1

Related Questions