Search⌘ K
AI Features

Replace a Set of Choices with FirstOrDefault

Explore how to refactor multiple conditional checks into a streamlined approach using LINQ's FirstOrDefault method. Understand replacing chained if statements with arrays of functions and applying the null-coalescing operator to simplify logic when selecting values from various sources.

How to Refactor a chain of conditionals with FirstOrDefault

When we need to find a value between multiple choices, we write consecutive if statements to check for a valid result every time.

For example, let’s find the next film to watch from one of three sources: the latest releases in cinemas, our friends’ ...