1

I am trying to use .Any() to validate if a list of elements is empty but there is a possibility it contains null elements and returns true, which I don't want. Is there a way to validate a list is empty, ignoring nulls?

return salesList.Any() ? salesList : null;

The null values I sometimes have in the list prevent this from ever returning null.

Sefe
  • 13,731
  • 5
  • 42
  • 55
Jalex
  • 72
  • 7

1 Answers1

13

Try:

return salesList.Any(item => item != null) ? salesList : null;

This overload of Enumerable.Any will only count the items that will match the predicate. In this case all non-null items.

Sefe
  • 13,731
  • 5
  • 42
  • 55