C#Generic List.Any()抛出System.NullReferenceException

Cap*_*chi 4 linq entity-framework generic-list c#-4.0

请考虑以下部分视图代码段

List<sellingPrice> Prices = ViewBag.Prices;
foreach (var mgmp in mg.messageGroup.messageGroupMessagePLUs)
{
    if (Prices.Any(x => x.pluId == mgmp.messagePLU.plu.pluId))
    {
        //do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

对于db中的特定产品,该行

if (Prices.Any(x => x.pluId == mgmp.messagePLU.plu.pluId))
Run Code Online (Sandbox Code Playgroud)

抛出System.NullReferenceException.检查代码显示mgmp 一个对象,而价格包含元素.但是,x的值为null.现在,我的印象是我只是测试是否存在满足我的测试的任何"x",而不是要求它返回"x".

这是一个非常恼人的问题.希望有人可以指出真正明显的解决方案.

Joh*_*son 5

尝试:

Prices.Any(x => x!=null && x.pluId == mgmp.messagePLU.plu.pluId)
Run Code Online (Sandbox Code Playgroud)

如果例如.messagePLU可以为null,则可能需要执行其他空检查