LINQ与NULL处理的字符串比较

Jib*_*hew 2 c# linq string-comparison

我正在使用这样的LINQ表达式

Attention attention = debtor_response.DebtorEntry
                .Address.AttentionList.Where(p => p.JobTitle.ToLower() == "valuetocheck")
                .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

这确实在正常情况下有效.但在某些情况下,它会返回一个异常

 Value cannot be null.\r\nParameter name: source 
Run Code Online (Sandbox Code Playgroud)

我想到的可能原因是

在某些情况下,JobTitle可能为null

那么如何才能在上面的LINQ中正确处理这个问题并摆脱异常

Amy*_*Amy 6

我怀疑AttentionList是null,因为方法签名Enumerable.Where是:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source,               <-------
    Func<TSource,?bool> predicate
)
Run Code Online (Sandbox Code Playgroud)

您的错误表示名为sourcenull 的参数,它与此扩展方法抛出的内容相匹配:

异常:ArgumentNullException
条件:source或predicate为null.

尝试将代码更改为以下内容:

Attention attention = debtor_response.DebtorEntry
    .Address
    .AttentionList?.Where(p => p.JobTitle.ToLower() == "valuetocheck")
               // ?
    .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

请注意第?3行添加了?如果AttentionList为null,则Null条件运算符将避免调用Where

我是怎么得出这个结论的

你得到了一个ArgumentNullException,但你只有三个函数调用:

Enumerable.Where          (extension)
Enumerable.FirstOrDefault (extension)
String.ToLower
Run Code Online (Sandbox Code Playgroud)

ToLower没有任何参数,因此可以排除.如果JobTitle是null,你会得到一个NullReferenceException.

两种扩展方法都有一个名为的参数source.但是,Where首先调用并且不能返回null值FirstOrDefault.所以罪魁祸首一定是Enumerable.Where.它的source参数为null,该参数为AttentionList.