C# TUTORIALS

C# LINQ Tutorial: Filtering, Sorting, Grouping and Joining

LINQ gives C# developers a consistent way to query collections and data sources using readable expressions.

What Is LINQ?

Language Integrated Query, or LINQ, lets you query objects and many other data sources with a common C# syntax.

Filtering with Where

var adults = people
    .Where(p => p.Age >= 18)
    .ToList();

Projecting with Select

var names = people
    .Select(p => p.Name)
    .ToList();

Sorting

var ordered = people
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Age)
    .ToList();

Grouping

var groups = people
    .GroupBy(p => p.Department)
    .ToList();

Joining Collections

var result = employees.Join(
    departments,
    e => e.DepartmentId,
    d => d.Id,
    (e, d) => new { e.Name, Department = d.Name });

Deferred Execution

Many LINQ operators return an enumerable that is evaluated when it is enumerated. Calling methods such as ToList() materializes the result immediately.

Best Practices

  • Keep LINQ expressions readable.
  • Avoid unnecessarily complex query chains.
  • Use Any() when you only need to know whether a match exists.
  • Use FirstOrDefault() when absence is a valid result.
  • Be aware of deferred execution and repeated enumeration.

Conclusion

LINQ is one of the most useful features in modern C#. Once you understand filtering, projection, ordering, grouping, and joins, you can write concise and expressive data-processing code.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.