How to Chain LINQ Methods in C# for Fluent Queries
You chain LINQ methods in C# by calling one method after another on a collection, like
Where(), Select(), and OrderBy(), each returning a new queryable sequence. This lets you build complex queries step-by-step in a fluent and readable way.Syntax
LINQ methods are chained by calling them one after another on an IEnumerable or IQueryable collection. Each method returns a new sequence that the next method operates on.
collection.Where(condition): Filters items..Select(transformation): Projects each item..OrderBy(keySelector): Sorts items.
csharp
var result = collection.Where(x => x > 5).Select(x => x * 2).OrderBy(x => x);
Example
This example shows how to chain LINQ methods to filter, transform, and sort a list of numbers.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 7, 3, 9, 2, 8 }; var query = numbers .Where(n => n > 3) // Keep numbers greater than 3 .Select(n => n * 10) // Multiply each by 10 .OrderBy(n => n); // Sort ascending foreach (var num in query) { Console.WriteLine(num); } } }
Output
70
80
90
Common Pitfalls
Common mistakes when chaining LINQ methods include:
- Forgetting that LINQ uses deferred execution, so the query runs only when enumerated.
- Mixing query syntax and method syntax incorrectly.
- Not understanding that each method returns a new sequence, so you must chain properly.
Example of a common mistake and fix:
csharp
// Wrong: Not chaining properly, calling methods separately without assignment var filtered = numbers.Where(n => n > 3); var transformed = numbers.Select(n => n * 10); // operates on original list, not filtered // Right: Chain methods so each operates on the previous result var correct = numbers.Where(n => n > 3).Select(n => n * 10);
Quick Reference
Tips for chaining LINQ methods:
- Start with a collection like
List<T>or array. - Use
Where()to filter items. - Use
Select()to transform items. - Use
OrderBy()orOrderByDescending()to sort. - Chain methods in the order you want operations applied.
- Remember LINQ queries run when you iterate over them.
Key Takeaways
Chain LINQ methods by calling one after another on collections to build queries fluently.
Each LINQ method returns a new sequence, so chain them to apply multiple operations.
LINQ uses deferred execution; queries run only when you enumerate the results.
Common methods include Where (filter), Select (transform), and OrderBy (sort).
Always chain methods in the correct order to get the expected results.