Reputation: 10590
I have this query in linq
var finalResults = (from r in results.AsEnumerable()
where DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
sometimes the SentOn
column could be null and I want to ignore these cases. how can I remove these null cases ?
if it is required we can do a staging (another) table that has just the not null values and i can continue
the table is results
so can I have another table, lets say results2
that doesn't have the null values or SentOn
?
Upvotes: 1
Views: 3643
Reputation: 2101
A null check should suffice.
var finalResults = results.AsEnumerable().Select(r => !r.IsNull(("SentOn"))
&& DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7)
You could create an Extension Method if this is a repeated pattern.
Upvotes: 0
Reputation: 3417
If the field SentOn
can be null
, you have to return DateTime?
instead of DateTime
.
Try:
var finalResults = (from r in results.AsEnumerable()
where r.Field<DateTime?>("SentOn") != null &&
DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
Alternatively, as pointed out in the comment, you can use DataRow.IsNull
.
var finalResults = (from r in results.AsEnumerable()
where !r.IsNull("SentOn") &&
DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
Upvotes: 2
Reputation: 14624
Try this
dt.AsEnumerable().Where(r => r.Field<DateTime?>("SentOn") != null && DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7);
Upvotes: 0
Reputation: 13676
You can check this in your .Where method with just 'if' statement:
var finalResults = results.AsEnumerable().Where(r =>
{
if(r.Field<DateTime?>("SentOn") == null) return false;
return DateTime.Now.Subtract(r.Field<DateTime?>("SentOn")).Minutes > 7;
}).ToList();
Upvotes: 0
Reputation: 9782
Just add the test in your WHERE
clause:
var finalResults = (from r in results.AsEnumerable()
where !r.IsNull("SentOn")
&& DateTime.Now.Subtract(
r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
Upvotes: 1
Reputation: 27627
You need to use the IsNull
method to check if the value is null first. This can be done as follows:
var finalResults = (from r in results.AsEnumerable()
where !r.IsNull("SentOn") &&
DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
Upvotes: 1