JohnB
JohnB

Reputation: 4359

How do I test DataTable fields for NULL in a C# LINQ query?

I have a piece of C# LINQ that I'm running against a datatable. The query is as follows:

var results = from myRow in dtDetails.AsEnumerable()
      where
           myRow.Field<DateTime>("ddceffect") > DateTime.Today.AddDays(-7)
           && myRow.Field<int>("ddcamtproc") == 0
      select myRow;

The field "ddcamrproc" is null.

I getting the following exception:

myRow.Field<int>("ddcamtproc")' threw an exception of type 'System.InvalidCastException'

How do I alter the LINQ query to test the fields for null before executing the rest of the query?

Thanks, JohnB

Upvotes: 0

Views: 1439

Answers (3)

Rajput
Rajput

Reputation: 2607

Since int is derived from system.struct so you need to write int? in Field to Field<int?>("ddcamtproc") == 0

Wherever in C# you are using any value type. if that is taking null value you can use nullable types(like int?)

Upvotes: 0

dotnetspark
dotnetspark

Reputation: 581

You could try this way as well.

var results = dtDetails.AsEnumerable()
              .Where(x => x.ddceffect > DateTime.Today.AddDays(-7) && 
                    x.ddcamtproc.HasValue && x.ddcamtproc.Value == 0);

OR

var results = dtDetails.AsEnumerable()
              .Where(x => x.ddceffect.Substract(DateTime.Today) == -7 
                 && x.ddcamtproc.HasValue && x.ddcamtproc.Value == 0);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460058

The Field method supports nullable teypes:

...   && myRow.Field<int?>("ddcamtproc") == 0

Upvotes: 2

Related Questions