Reputation: 4359
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
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
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
Reputation: 460058
The Field
method supports nullable teypes:
... && myRow.Field<int?>("ddcamtproc") == 0
Upvotes: 2