LINQ and Declarative Programming
We work with collections regularly, whether it’s comments on a post, an invoice of purchased items, or guests in a reservation. We can use
foreach, and other loops with collections. But with LINQ, we can write more concise and readable code. Let’s see why!
Declarative vs. imperative programming
The distinction between declarative and imperative programming is what makes LINQ different from loops.
LINQ is declarative. That means we write our code stating the results we want instead of doing every step to get those results.
With LINQ, we write code to filter a collection based on a condition. This is instead of writing code that grabs the first element of a collection, then checks if it satisfies a condition, then moves to the next element, then checks again, and so on.
Let’s look at an example. When we order at a restaurant, we do it declaratively. We tell the waiter what we want, something like “A cheese hamburger, please.” We don’t say to the waiter, “Put 500 grams of beef in a hot pan and fry it on each side for five minutes,” listing all the steps of the recipe. That would be ordering imperatively.
LINQ is a better alternative to query collections than loops. With LINQ, we separate the results from the steps to get them. This lets us write more expressive code.
Our catalog of movies
Let’s get to the code.
Let’s start with the collection of movies we’ve watched. We have a
Movie class with a
Rating. Let’s find our favorite movies, ones with a rating greater than 4.5.