Five Common LINQ Methods in Pictures

canro91

Cesar Aguirre

Posted on June 1, 2022

Five Common LINQ Methods in Pictures

I originally published this post on my blog a couple of weeks ago. It's part of a post series about LINQ.


LINQ is the most distinctive of all C# features — In fact, LINQ is the best C# feature.

But, if you're learning LINQ for the first time, it can be daunting to learn all LINQ methods at once. Don't try it.

Here are the five most common LINQ methods in pictures.

Let's work with a list of our favorite movies. Let's write a Movie class (or a record, if you like) with a name, release year, and a rating. And, put our favorite movies in a list.

var movies = new List<Movie>
{
    new Movie("Titanic", 1998, 4.5f),
    new Movie("The Fifth Element", 1997, 4.6f),
    new Movie("Terminator 2", 1991, 4.7f),
    new Movie("Avatar", 2009, 5),
    new Movie("Platoon", 1986, 4),
    new Movie("My Neighbor Totoro", 1988, 5)
};
Enter fullscreen mode Exit fullscreen mode

1. Where

The Where method returns a new collection with only the elements that meet a given condition.

The Where method works like a filter on collections. Think of Where as a replacement for a foreach with an if in it.

Let's filter our list of movies to keep only those with a rating greater than or equal to 4.5.

var favorites = movies.Where(movie => movie.Rating >= 4.5);
Enter fullscreen mode Exit fullscreen mode

This query would be something like this,

Favorite films filtered by rating
Let's keep the films with a rating greater than 4.5

We're using arrows to display our LINQ queries. But, the output of a LINQ query is lazy-evaluated: the actual result of a LINQ query is evaluated until we loop through its result.

2. Select

The Select method applies a function to transform every element of a collection.

Let's find only the names of our favorite movies.

var favorites = movies.Where(movie => movie.Rating >= 4.5)
                      .Select(movie => movie.Name);
Enter fullscreen mode Exit fullscreen mode

This query would be,

Name of our favorite films filtered by rating
Let's keep only the names of our favorite films

3. Any

The Any method checks if a collection has at least one element matching a condition. Unlike Where and Select, Any doesn't return a new collection, but either true or false.

Let's see if we have watched movies with a low rating.

var hasBadMovies = movies.Any(movie => movie.Rating < 2);
Enter fullscreen mode Exit fullscreen mode

This query would be,

At least one film with a low rating
Do we have films with a low rating?

4. GroupBy

The GroupBy method returns a collection of "buckets" organized by a key. Also, GroupBy transforms each bucket of elements.

Let's count the films with the same rating.

var groupedByRating = movies.GroupBy(movie => movie.Rating,
                                    (rating, movies) => new // 👈
                                    {
                                        Rating = rating,
                                        Count = movies.Count()
                                    });
Enter fullscreen mode Exit fullscreen mode

The second parameter of the GroupBy is a Func with the grouping key and the elements of each group as parameters.

This query would be,

Count of films grouped by rating
Let's count the films with the same rating

5. First & FirstOrDefault

The First and FirstOrDefault methods return the first element in a collection or the first one matching a condition. Otherwise, First throws an exception, and FirstOrDefault returns the default value of the collection type.

Let's find the oldest film we have watched.

var oldest = movies.OrderBy(movie => movie.ReleaseYear)
                   .First(); // 👈
Enter fullscreen mode Exit fullscreen mode

This query would be,

Oldest film we have watched
Let's find the oldest film we have watched

Voilà! These are five LINQ methods you'll use most often: Where, Select, Any, Group, and FirstOrDefault.

Of course, LINQ has more methods. Plenty! But, you will get your back covered 80% of the time with these five methods.


Want to write more expressive code for collections? Join my Udemy course, Getting Started with LINQ, and master everything you need to work productively with LINQ — all in less than two hours!

Happy LINQ time!

💖 💪 🙅 🚩
canro91
Cesar Aguirre

Posted on June 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related