How to check for any null values within a list before processing further?

Viewed 173

I'm passing a list to a method that operates on the list. However first I want to iterate over the list and check whether or not there are any null values within the list before any further processing takes place.

Initally I thought using the IEnumerable.All() method would help with this, however this method actually checks that all elements of the list satisfy a condition, I'd like to check each element in turn and if any are null then handle this.

This is the (non-working) code that I have already. I'm not sure how I would adapt this for use within an if statement condition.

if (questions == null || questions.Any() == false || questions.All(q => q == null))
{
    throw new ArgumentException("Exception raised.");
}

Essentially I want to check:

  1. Questions isn't null.
  2. Questions isn't empty.
  3. Any elements held within questions aren't null values.

The first two have been done, it's just the third.

3 Answers

You can use this more concise version that uses Any and the ?-operator:

bool valid = questions?.Any(q => q != null) == true;
if (!valid)
   throw new ArgumentException("Exception raised.");

The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.

I think you want to

if (questions != null && questions.Any() && questions.All(q => q != null))

I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:

if (null == questions)
  throw new ArgumentNullException(nameof(questions));
else if (questions.All(q => q == null))
  throw new ArgumentException("At least one not null question expected.",
                               nameof(questions)); 

Or even into three: when implementing a contract, in your case it is

  1. questions isn't null.
  2. questions isn't empty.
  3. Any elements held within questions aren't null values.

try throw separate exception for each violation:

 if (null == questions)
   throw new ArgumentNullException(nameof(questions));
 else if (!questions.Any())
   throw new ArgumentException("Questions must not be empty.",
                                nameof(questions)); 
 else if (questions.Any(item => null == item))
   throw new ArgumentException("Null questions are not allowed.",
                                nameof(questions)); 

Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).

Related