Home

Published

- 2 min read

7 powerful LINQ methods you’ll wish you knew sooner

img of 7 powerful LINQ methods you’ll wish you knew sooner
Reach 7,100+ engaged devs by sponsoring this newsletter

One of the greatest gifts .NET has ever given us is LINQ.

A way to write expressive, readable, and efficient queries directly in C#.

  • It turns nested loops into elegant one-liners.
  • It makes filtering, sorting, and transforming data easy.
  • It saves you from the nightmare of manual data manipulation.

But it also has many methods that might be unfamiliar to most developers.

So in this post, I’ll share 7 that you might not be aware of.

But can become your favorite in the future.

So buckle up, some great LINQ methods are heading your way.

1. SelectMany

Flattens a collection of collections into a single collection.

   var lists = new[]
{
    new[] { 1, 2 },
    new[] { 3, 4 }
};

var flattened = lists.SelectMany(x => x);
// Output - single collection: 1, 2, 3, 4

2. CountBy

Groups elements by a specified key and returns the count of elements in each group.

   var words = new[] { "apple", "banana", "apple", "orange", "banana", "apple" };

var wordCounts = words.CountBy(word => word);
// Output:
// apple: 3
// banana: 2
// orange: 1

3. OfType

Filters a collection by a specific type.

   var mixed = new object[] { 1, "hello", 2.5, 3 };

var numbers = mixed.OfType<int>();
// Output: 1, 3

4. DistinctBy

Removes duplicates based on a selected key.

   var products = new[]
{
    new { Name = "Apple", Category = "Fruit" },
    new { Name = "Carrot", Category = "Vegetable" },
    new { Name = "Banana", Category = "Fruit" }
};

var noDuplicates = products.DistinctBy(p => p.Category);
// Output:
// Apple
// Carrot

5. Intersect

Finds common elements between two collections.

   var a = new[] { 1, 2, 3 };
var b = new[] { 2, 3, 4 };

var common = a.Intersect(b);
// Output: 2, 3

6. Chunk

Splits a collection into fixed-size chunks.

   var numbers = new[] { 1, 2, 3, 4, 5, 6, 7 };

var chunks = numbers.Chunk(3);
// Output: [1, 2, 3], [4, 5, 6], [7]

7. Zip

Combines two collections element by element.

   var letters = new[] { "A", "B", "C" };
var numbers = new[] { 1, 2, 3 };

var zipped = letters.Zip(numbers, (l, n) => $"{l}{n}");
// Output: A1, B2, C3

If you’re still just using foreach and Select for every case, you’re missing out on a lot of LINQ gems that could make your code more readable and efficient.

If you're a .NET developer who's looking to level up your career, but struggles to keep up with the latest cool stuff in .NET...

Every Friday I share actionable .NET advice, insights, and tips to learn the latest .NET concepts, frameworks, and libraries inside my FREE newsletter.

Join here 7,100+ other developers