LINQ method you are probably not aware of

iamprovidence
2 min readSep 2, 2022

--

The more project I have changed, the more I got convinced that there is some conspiracy theory and Microsoft hiding from us secret knowledge. But don't worry, today I will discover the biggest mystery of all time.

Have you seen developers break linq statements and write code like this to avoid null reference:

Sure, that seems harmless, but only imagine it in real world scenario appearing somewhere in the middle of your linq chain😃

Or let's look to another example. Can you spot what is wrong here?

A careful reader will notice calling Max on empty collection will result in InvalidOperationException with message ‘Sequence contains no elements’.

As a result I am constantly spotting next code:

How clumsy is that! We always need to check whenever collection has any items in it.

It seems like Microsoft has poorly thought it through.

In the end, they had mercy on us and in .net6 introduces some linq improvements. Finally, FirstOrDefault support default value:

But would you believe me if tell you it was always available?🤔

Among variety of linq method there is one special that does not get enough recognition as others —DefaultIfEmpty.

The name speaks for itself. It does what you would expect from it. When source collection does not contain any element a new collection with default value in it will be returned.

As a result, we can rewrite our first example with single linq chain:

Remember that wacky piece of code with Max. You no longer need to validate whenever there is any item in collection, just use DefaultIfEmpty, as follow

That was your missing piece of puzzle. Hope with received knowledge, you would be able to make your code less verbose and more compact.

Do not hesitate to share this knowledge with your college 😉
☕️ Buy me a coffee with link below to support what I am doing here
✅ Follow to learn more tricks and happy coding

--

--

iamprovidence

👨🏼‍💻 Full Stack Dev writing about software architecture, patterns and other programming stuff https://www.buymeacoffee.com/iamprovidence