[英]c# linq how to check for null values in the same column that i need to be not null
I have this query in linq 我在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. 有时
SentOn
列可能为null,而我想忽略这些情况。 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
? 该表是
results
,所以我可以有另一个表,可以说results2
不具有空值或SentOn
?
If the field SentOn
can be null
, you have to return DateTime?
如果
SentOn
字段可以为null
,则必须返回DateTime?
instead of DateTime
. 而不是
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
. 或者,如注释中指出的,您可以使用
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();
Just add the test in your WHERE
clause: 只需在您的
WHERE
子句中添加测试:
var finalResults = (from r in results.AsEnumerable()
where !r.IsNull("SentOn")
&& DateTime.Now.Subtract(
r.Field<DateTime>("SentOn")).Minutes > 7
select r
).ToList();
You need to use the IsNull
method to check if the value is null first. 您需要使用
IsNull
方法首先检查该值是否为null。 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();
You can check this in your .Where method with just 'if' statement: 您可以使用.if语句在.Where方法中进行检查:
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();
尝试这个
dt.AsEnumerable().Where(r => r.Field<DateTime?>("SentOn") != null && DateTime.Now.Subtract(r.Field<DateTime>("SentOn")).Minutes > 7);
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. 如果这是重复模式,则可以创建扩展方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.