# 5 LINQ methods you should know

You know Where and Select, and you still catch yourself writing loops with counters, flags and a comma too many. Five LINQ methods replace those loops.

By Gregor Dzierzon · Published November 20, 2026

![On the left, a tangled ball of string with a small counter dial and a little red flag knotted into it; on the right, a tidy pegboard with five tools hanging in a row, labeled OrderByDescending, Any, FirstOrDefault, string.Join and GroupBy](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/82984784ea794960be92578b108d24d7.webp)

You've learned `Where` and `Select`, and LINQ finally makes sense. Then a real request comes in ("show the three most
expensive products", "is anything out of stock?") and you're back to writing a loop with a counter, a `bool` flag and a
`break`.

Those loops work. They're also where the out-of-range errors and the stray commas live. Here are five LINQ methods that
replace them, each shown as the loop you'd write and the LINQ that does the same job.

Every example uses a store's `List<Product>`, where each product has a `ProductName`, a `CategoryName`, a `UnitPrice`
and its `UnitsInStock`:

| Product | Category | Price | Units in stock |
|---|---|---|---|
| Chai | Beverages | 18.00 | 39 |
| Chang | Beverages | 19.00 | 17 |
| Aniseed Syrup | Condiments | 10.00 | 13 |
| Chef Anton's Gumbo Mix | Condiments | 21.35 | 0 |
| Ikura | Seafood | 31.00 | 31 |
| Konbu | Seafood | 6.00 | 24 |
| Tofu | Produce | 23.25 | 35 |
| Alice Mutton | Meat/Poultry | 39.00 | 0 |

## 1. The top three by price: OrderByDescending and Take

**Before:** copy the list, sort the copy, then count to three.

```csharp
List<Product> sorted = new List<Product>(products);
sorted.Sort((a, b) => b.UnitPrice.CompareTo(a.UnitPrice));

List<string> premiumPicks = new List<string>();
for (int i = 0; i < 3; i++)
{
    premiumPicks.Add(sorted[i].ProductName);
}
```

You need the copy because `Sort` reorders the list itself
([List.Sort](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort)), and the
rest of the page still wants the products in their original order. And on the day the store has only two products,
`sorted[2]` stops the page with an `ArgumentOutOfRangeException`.

**After:**

```csharp
List<string> premiumPicks = products
    .OrderByDescending(product => product.UnitPrice)
    .Take(3)
    .Select(product => product.ProductName)
    .ToList();
// premiumPicks: Alice Mutton, Ikura, Tofu
```

`OrderByDescending` builds a new, sorted sequence and leaves `products` as it was
([Enumerable.OrderByDescending](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending)).
`Take(3)` gives *up to* three: when there are fewer, it gives all of them, with no exception
([Enumerable.Take](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take)).

## 2. A yes-or-no question: Any

**Before:**

```csharp
bool anyOutOfStock = false;
foreach (Product product in products)
{
    if (product.UnitsInStock == 0)
    {
        anyOutOfStock = true;
        break;
    }
}
```

**After:**

```csharp
bool anyOutOfStock = products.Any(product => product.UnitsInStock == 0);
// true
```

Like the `break`, `Any` stops at the first match
([Enumerable.Any](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any)). Its partner is `All` (does
every item match?). To ask "does no item match?", put a `!` in front: `!products.Any(...)`.

## 3. The first one, or a fallback: FirstOrDefault

**Before:** a `string` that starts as `null`, a loop, and a `break`. When nothing matches, the variable stays `null`, and
the page crashes later with a `NullReferenceException`.

**After:**

```csharp
string firstSeafood = products
    .Where(product => product.CategoryName == "Seafood")
    .Select(product => product.ProductName)
    .FirstOrDefault("Nothing in this category");
// firstSeafood: Ikura
```

The value you pass is what you get back when nothing matches
([Enumerable.FirstOrDefault](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault)), so
the variable always holds a real `string`. Leave it out, and `FirstOrDefault` gives the type's default value instead:
`null` for a `string`, `0` for an `int`. Passing a fallback has worked since .NET 6
([What's new in .NET 6](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-6)); in older code you'll see
`FirstOrDefault() ?? "Nothing in this category"`, which does the same job.

## 4. One line of names, no comma too many: string.Join

**Before:**

```csharp
string names = "";
foreach (Product product in products)
{
    if (product.UnitsInStock == 0)
    {
        names += product.ProductName + ", ";
    }
}
// names: "Chef Anton's Gumbo Mix, Alice Mutton, ": one comma too many
```

**After:**

```csharp
string outOfStock = string.Join(", ", products
    .Where(product => product.UnitsInStock == 0)
    .Select(product => product.ProductName));
// outOfStock: "Chef Anton's Gumbo Mix, Alice Mutton"
```

`string.Join` puts the separator *between* the items, never after the last one
([String.Join](https://learn.microsoft.com/en-us/dotnet/api/system.string.join)). It isn't a LINQ method; it belongs to
`string`. But it takes any sequence of strings, so it's how a LINQ chain becomes one line of text.

## 5. Groups and counts: GroupBy

**Before:** a dictionary, a check whether each category is a key yet, and a `+ 1` in the right place.

**After:**

```csharp
Dictionary<string, int> countByCategory = products
    .GroupBy(product => product.CategoryName)
    .ToDictionary(group => group.Key, group => group.Count());
// Beverages 2, Condiments 2, Seafood 2, Produce 1, Meat/Poultry 1
```

`GroupBy` sorts the products into groups. Each group has a `Key`, the category its products share, and is itself a
collection you can count, total or list. The groups come out in the order their first product appears
([Enumerable.GroupBy](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby)).

When a count is all you need, .NET 9 added a shortcut: `products.CountBy(product => product.CategoryName)` gives the
same category-and-count pairs without building the groups
([What's new in .NET 9 libraries](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/libraries)).

## The rest, in the lessons

These five cover the requests you'll hear most often. Two lessons go further, and each ends with a Do It you solve right
on the page:

- [What is LINQ?](https://www.ask-codey.com/lessons/linq-what-is-linq?course=csharp-full-stack-bootcamp) shows how a chain goes from a
  collection, through each method, to a result, and why a query runs when you use its results, not when you write it.
- [Common LINQ Methods](https://www.ask-codey.com/lessons/linq-common-linq-methods?course=csharp-full-stack-bootcamp) teaches methods 1, 2, 3
  and 5 in depth, plus `ThenBy` for breaking ties, `Count`, `Sum`, `Average`, `Min` and `Max`, `First` and when it
  throws, `Skip` for pages of results, and `Distinct`.

Writing Java too? [Java streams beyond filter and map](https://www.ask-codey.com/blog/java-streams-beyond-filter-and-map) does the same five jobs
with Java streams.

Next time you start typing `bool found = false;`, stop and ask which LINQ method already does it.

## Sources

- Microsoft, [List.Sort](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort), the .NET API documentation: `Sort` sorts the elements of the list itself.
- Microsoft, [Enumerable.OrderByDescending](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending), the .NET API documentation: sorts the elements of a sequence in descending order.
- Microsoft, [Enumerable.Take](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take), the .NET API documentation: if the count is more than the number of elements, all of them are returned.
- Microsoft, [Enumerable.Any](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any), the .NET API documentation: enumeration stops as soon as the result can be determined.
- Microsoft, [Enumerable.FirstOrDefault](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault), the .NET API documentation: returns the first element, or a specified default value if there are none.
- Microsoft, [What's new in .NET 6](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-6): the `FirstOrDefault` overloads that take a default value.
- Microsoft, [String.Join](https://learn.microsoft.com/en-us/dotnet/api/system.string.join), the .NET API documentation: joins the members of a collection with the separator between each member.
- Microsoft, [Enumerable.GroupBy](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby), the .NET API documentation: groups come out in the order of the elements that produced each group's first key.
- Microsoft, [What's new in .NET 9 libraries](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/libraries): the new `CountBy` method.

Tags: [c-sharp](https://www.ask-codey.com/blog?tag=c-sharp), [linq](https://www.ask-codey.com/blog?tag=linq)

## Glossary subjects

- [C#](https://www.ask-codey.com/glossary/subjects/c-sharp)

## More posts

- Previous: [MySQL vs. SQL Server: the same jobs, different functions](https://www.ask-codey.com/blog/mysql-vs-sql-server-functions)
- Next: [Comparing C# LINQ and Java Streams: 5 common uses](https://www.ask-codey.com/blog/csharp-linq-vs-java-streams)

Source: https://www.ask-codey.com/blog/five-linq-methods-you-should-know
