C# LINQ Tutorial: Query Collections Easily

LINQ, or Language Integrated Query, provides a powerful way to work with collections in C#. It allows developers to filter, sort, transform, group, and search data using concise and readable code.

What is LINQ in C#?

LINQ is a set of features in C# that allows queries to be written directly in the language. It works with arrays, lists, collections, databases, XML, and other data sources.

CSHARP
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };

var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var number in evenNumbers)
{
    Console.WriteLine(number);
}

Why Use LINQ?

  • Write shorter and cleaner collection queries
  • Filter data easily
  • Sort and group collections
  • Transform objects into new data
  • Improve readability of collection-processing code

Using Where

The Where method filters a collection based on a condition.

CSHARP
var ages = new List<int> { 15, 18, 21, 25, 30 };

var adults = ages.Where(age => age >= 18);

Using Select

The Select method transforms each item in a collection into another value or object.

CSHARP
var names = new List<string> { "Alice", "Bob", "Charlie" };

var lengths = names.Select(name => name.Length);

Sorting with OrderBy

OrderBy sorts elements in ascending order, while OrderByDescending sorts them in descending order.

CSHARP
var numbers = new List<int> { 40, 10, 30, 20 };

var ascending = numbers.OrderBy(n => n);
var descending = numbers.OrderByDescending(n => n);

Using First and FirstOrDefault

First returns the first matching element, while FirstOrDefault returns the default value when no matching element exists.

CSHARP
var numbers = new List<int> { 10, 20, 30 };

var first = numbers.First();
var result = numbers.FirstOrDefault(n => n > 100);

Using Any and All

Any checks whether at least one element satisfies a condition. All checks whether every element satisfies a condition.

CSHARP
bool hasLargeNumber = numbers.Any(n => n > 25);
bool allPositive = numbers.All(n => n > 0);

Using GroupBy

GroupBy organizes elements into groups based on a selected key.

CSHARP
var students = new[]
{
    new { Name = "Alice", Grade = "A" },
    new { Name = "Bob", Grade = "B" },
    new { Name = "John", Grade = "A" }
};

var grouped = students.GroupBy(s => s.Grade);

LINQ Method Table

MethodPurposeExample
WhereFilter elementsWhere(x => x > 10)
SelectTransform elementsSelect(x => x.Name)
OrderBySort ascendingOrderBy(x => x.Name)
GroupByCreate groupsGroupBy(x => x.Category)
FirstGet first elementFirst()
AnyCheck for matching elementsAny(x => x > 10)
CountCount elementsCount()

Combining LINQ Methods

LINQ methods can be chained together to build more complex queries while keeping the code readable.

CSHARP
var result = students
    .Where(s => s.Grade == "A")
    .Select(s => s.Name)
    .OrderBy(name => name);

LINQ Query Syntax

C# also supports query syntax, which provides an SQL-like way to express LINQ queries.

CSHARP
var result = from student in students
             where student.Grade == "A"
             select student.Name;

Deferred Execution

Many LINQ queries use deferred execution, meaning the query is evaluated when its results are actually enumerated rather than immediately when the query is created.

CSHARP
var query = numbers.Where(n => n > 10);

foreach (var number in query)
{
    Console.WriteLine(number);
}

Real-World Applications

  • Filtering products in e-commerce applications
  • Searching users in web applications
  • Sorting records in dashboards
  • Grouping sales data
  • Transforming database query results

Common Mistakes to Avoid

  • Creating unnecessarily complex LINQ chains
  • Ignoring deferred execution
  • Calling ToList repeatedly without need
  • Using LINQ when a simple loop is clearer
  • Loading large datasets unnecessarily

Advanced LINQ Concepts

  • IEnumerable and IQueryable
  • Deferred execution
  • Projection
  • Joins
  • Aggregation
  • Expression trees
  • LINQ with Entity Framework

Practice Exercises

  • Filter a list of numbers
  • Find products above a specific price
  • Sort a list of users by name
  • Group employees by department
  • Find the highest value using Max
  • Calculate an average using Average

Conclusion

LINQ makes collection processing in C# more expressive and convenient. By learning methods such as Where, Select, OrderBy, GroupBy, Any, and First, developers can write clean and maintainable data-processing code.

Note: Note: Choose LINQ when it improves clarity, but avoid overly complicated queries that make the code harder to understand or inefficient for large datasets.