2

I am using a LINQ expression like this

Attention attention = debtor_response.DebtorEntry
                .Address.AttentionList.Where(p => p.JobTitle.ToLower() == "valuetocheck")
                .FirstOrDefault();

This indeed worked in normal cases. But under some cases it returns an exception

 Value cannot be null.\r\nParameter name: source 

The possible reasons in my thoughts are

JobTitle might be null in some cases

So how can i handle this correctly in the above LINQ and get rid of the exception

0

1 Answer 1

6

I suspect AttentionList is null, because the method signature for Enumerable.Where is:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source,               <-------
    Func<TSource, bool> predicate
)

Your error said that a parameter named source is null, which matches what this extension method throws:

Exception: ArgumentNullException
Condition: source or predicate is null.

Try changing your code to the following:

Attention attention = debtor_response.DebtorEntry
    .Address
    .AttentionList?.Where(p => p.JobTitle.ToLower() == "valuetocheck")
               // ↑
    .FirstOrDefault();

Notice the added ? on line 3? If AttentionList is null, the Null-conditional Operator will avoid calling Where

How did I come to this conclusion

You're getting an ArgumentNullException, but you only have three function calls:

Enumerable.Where          (extension)
Enumerable.FirstOrDefault (extension)
String.ToLower

ToLower doesn't have any parameters, so it can be ruled out. And if JobTitle were null, you would get a NullReferenceException.

Both extension methods have a parameter called source. However, Where is called first and can't return a null value to FirstOrDefault. So the culprit must be Enumerable.Where. It's source parameter is null, and that parameter is AttentionList.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.