How to avoid Null checks with LINQ?

We are all familiar with LINQ, but we don’t quite reveal its power in our code. I’ll try to explain to you, one technique that I use in my projects on daily basis.

Imagine a typical situation, we have a method which gives Product by its Id, but if it is not found returns null:

And the one who is going to call this method, should write code like this

We can avoid this null check if we look at this problem from the other side.

Why null is bad idea you can see in many of articles which gives google search results

What if every time when we can’t find something we will return an empty thing, otherwise a thing with one element.

This example will help:

Dear, bring me a glass of cold water, or if the water is hot then empty glass. And I will decide what to do with it.


Then an example of the code in here:

Instead of thing we use List<T> and return empty list if we can’t find product or list with one element instead.

And code on the usage side:

Do you see a difference? I don’t.

But we can go further. For this we need another example.

What if after retrieving product, we want find details about it on Amazon?

If we use the usual approach, then code will look like this:

But if we do not violate the agreement that was adopted above, that we always return thing with element, our code might look like this:

.DetailsFromAmazon() also returns List<ProductDetails>
.SelectMany does very simple thing it flattens list of lists (two dimensional list) and returns one flat (one dimensional) list.
// [[1,2],[3,4,5]] - this is List of Lists
new List<List<int>>()
new List<int>() { 1, 2 },
new List<int>() { 3, 4, 5 }
.SelectMany(list => list); // [1, 2, 3, 4, 5] - this is flat list
More about .SelectMany you can see in Jon Skeet’s post

Here the benefits are already noticeable, we avoid one null check. Let’s go further, don’t stop.

We can write one small extension method for IEnumerable<T> with name Match, which takes two functions, look at the code:

And we can change code below on this:

That’s all.

In next article I will show what kind of helpers I use every day on projects at my job.

I hope you enjoyed. :)