Yes, list?.Where(i => i > 1)
is a legit expression, which called "null propagation operator".
On of the problem of using null propagation operator is that you will start writing code like this
var result = list?.Where(i => i > 1)?.Select(i => i * 2)?.Where(i => i % 2 == 0)?.ToList();
// result can be null and still requires check for null
.. what are other elegant solutions you know?
Other elegant solution would be to make sure that whenever function returns a collection it never return null
but an empty collection.
Such convention will make your code easier to read and understand actual intentions of the code, make it easy to test (less test cases to test), less "noisy null checks".
Notice that LINQ extension methods never return null
.
If you are using libraries which returns null
for a collection but you don't have access to the code - "convert" null
to an empty collection and continue using as valid collection.
var checkedList = givenList ?? Enumerable.Empty<int>();
checkedList.Where(i => i > 1).ToList();
If you find yourself doing this a lot, create an extension method.
public IEnumerable<T> EmptyIfNull(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Usage
var result = givenList.EmptyIfNull().Where(i => i > 1).ToList();