开发者

Linq: comparison with nonexisting value should not cause the exception, but it does

开发者 https://www.devze.com 2023-02-04 14:14 出处:网络
Given I don\'t know if the parameter will be null or not and I want to use it in the following way: if Param != null then compare with its id

Given I don't know if the parameter will be null or not and I want to use it in the following way: if Param != null then compare with its id if Param == null then compare with null.

Something like that:

var c = from cat in context.Categories
where ParamCat != null && cat.ParentId == ParamCat.Id 
||
ParamCat == null && cat.ParentId == null
select c;

If ParamCat is null as soon as I try to get开发者_运维百科 something from c (for example c.Count()) it throws the exception.

Usually when we use some kind of condition it stop comparison as soon as condition fail especially if we use AND. For example this code will not cause any exception:

if (ParamCat != null &&  cat.ParentId == RaramCat.Id)
{
}

If so, why the linq code above throw exception? (Null reference)

Thanks


You need to group your && expressions with parentheses in order to get the compiler to evaluate them in that order:

var c = from cat in context.Categories
where (ParamCat != null && cat.ParentId == ParamCat.Id)
||
(ParamCat == null && cat.ParentId == null)
select cat;


Try:

var c = from cat in context.Categories
where (ParamCat == null && cat.ParentId == null)
  || (ParamCat != null && cat.ParentId == ParamCat.Id) 
select cat;

( and ) can make a big difference... :)

0

精彩评论

暂无评论...
验证码 换一张
取 消