Five Common LINQ Methods in Pictures
Tags: beginners, csharp, dotnet
Published: 2022-06-01 15:38:25

_I originally published this post on [my blog](https://canro91.github.io/2022/05/16/LINQMethodsInPictures/) a couple of weeks ago. It's part of a post series about LINQ._

One of the best C# features is LINQ. I would say it's the most distinctive of all [C# features](https://canro91.github.io/2021/09/13/TopNewCSharpFeatures/). But, if you're learning LINQ for the first time, it can be daunting to learn all LINQ methods at once. These are five of the 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.

```csharp
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)
};
```

## 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.

```csharp
var favorites = movies.Where(movie => movie.Rating >= 4.5);
```

This query would be something like this,

<figure><img src="https://canro91.github.io/assets/posts/2022-05-16-LINQMethodsInPictures/Where.png" alt="Favorite films filtered by rating"><figcaption>Let's keep the films with a rating greater than 4.5</figcaption>
</figure>

We're using arrows to display our LINQ queries. But, the output of a LINQ query is lazy-evaluated. It means 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.

```csharp
var favorites = movies.Where(movie => movie.Rating >= 4.5)
                      .Select(movie => movie.Name);
```

This query would be,

<figure><img src="https://canro91.github.io/assets/posts/2022-05-16-LINQMethodsInPictures/WhereAndSelect.png" alt="Name of our favorite films filtered by rating"><figcaption>Let's keep only the names of our favorite films</figcaption>
</figure>

<figure>
<img src="https://source.unsplash.com/HqA7l8IbhmY/600x400" alt="VHS in a film store" />

<figcaption>Did you have VHS at home? Photo by <a href="https://unsplash.com/@delaneyvan?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Delaney Van</a> on <a href="https://unsplash.com/s/photos/movies?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a></figcaption>
</figure>

## 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.

```csharp
var hasBadMovies = movies.Any(movie => movie.Rating < 2);
```

This query would be,

<figure><img src="https://canro91.github.io/assets/posts/2022-05-16-LINQMethodsInPictures/Any.png" alt="At least one film with a low rating"><figcaption>Do we have films with a low rating?</figcaption>
</figure>

## 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.

```csharp
var groupedByRating = movies.GroupBy(movie => movie.Rating,
                                    (rating, movies) => new
                                    {
                                        Rating = rating,
                                        Count = movies.Count()
                                    });
```

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,

<figure><img src="https://canro91.github.io/assets/posts/2022-05-16-LINQMethodsInPictures/GroupByGroups.png" alt="Count of films grouped by rating"><figcaption>Let's count the films with the same rating</figcaption>
</figure>

## 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.

```csharp
var oldest = movies.OrderBy(movie => movie.ReleaseYear)
                   .First();
```

This query would be,

<figure><img src="https://canro91.github.io/assets/posts/2022-05-16-LINQMethodsInPictures/First.png" alt="Oldest film we have watched"><figcaption>Let's find the oldest film we have watched</figcaption>
</figure>

Voilà! These are five LINQ methods I use most often: Where, Select, Any, Group, and FirstOrDefault. Of course, LINQ has more. But, you will get your back covered 80% of the time with these five methods.

***

_Hey! I'm Cesar, a software engineer and lifelong learner. If you want to learn more about this subject, check my course [Getting Started with LINQ](https://bit.ly/csarag-linq-course) on Educative where I cover other LINQ methods in depth._

_Happy LINQ time!_