在我的LINQ查询中检查null

时间:2012-09-03 16:18:35

标签: linq linq-to-sql

下午 如果下面的行为空

,我似乎无法理解如何忽略
where ((double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo))

正如您在下面的代码中所看到的,我能够在它的字符串时执行此操作。但我有价格问题。有人可以为我解释一下吗?

from a in dc.aboProducts
join t in dc.tweProducts on a.sku equals t.sku
where (string.IsNullOrEmpty(productSku) || productSku == t.sku)
where (string.IsNullOrEmpty(productAsin) || productAsin == a.asin)
where (string.IsNullOrEmpty(productName) || t.title.Contains(productName))
where (string.IsNullOrEmpty(productBrand) || t.brand.Contains(productBrand))
where ((double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo))
select new GetProducts

UPDATE:我基本上是在发送一大堆项目来搜索我的MS SQL数据库,其中一些可能是字符串的NULL。价格也可能是空的,因为不需要一直这样。因此,如果价格为空,我不需要使用它们。

非常感谢。

2 个答案:

答案 0 :(得分:0)

检查twePrice是否为空,例如:

where (t.twePrice != null && (double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo))

@thatuxguy,我猜你需要这样的东西。如果twePrice为null,则下面的代码忽略条件。

where (t.twePrice == null ? true : (double)t.twePrice >= priceFrom && (double)t.twePrice <= (priceTo))

祝你好运!!

答案 1 :(得分:0)

以下可能就足够了:

where ((priceFrom == null || (double)t.twePrice >= priceFrom) && (priceTo == null || (double)t.twePrice <= priceTo))

为了便于阅读,它可能会分成两部分:

where (priceFrom == null || (double)t.twePrice >= priceFrom) 
where (priceTo == null || (double)t.twePrice <= priceTo)