0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Where in C# for Filtering Collections

Use the Where method in LINQ to filter collections based on a condition expressed as a lambda expression. It returns all elements that satisfy the condition, allowing you to easily select specific items from lists or arrays.
📐

Syntax

The Where method takes a lambda expression as a condition to filter elements from a collection.

  • collection.Where(item => condition): Filters collection by keeping elements where condition is true.
  • item: Represents each element in the collection during filtering.
  • condition: A boolean expression that decides if the element is included.
csharp
var filtered = collection.Where(item => item > 5);
💻

Example

This example shows how to filter a list of numbers to get only those greater than 5 using Where.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 3, 6, 8, 2, 10 };
        var filteredNumbers = numbers.Where(n => n > 5);

        foreach (var num in filteredNumbers)
        {
            Console.WriteLine(num);
        }
    }
}
Output
6 8 10
⚠️

Common Pitfalls

One common mistake is forgetting that Where returns an IEnumerable and does not modify the original collection. Also, using complex conditions without parentheses can cause logic errors.

Another pitfall is not including using System.Linq;, which is required to use Where.

csharp
using System;
using System.Collections.Generic;
// Missing using System.Linq; causes error

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3 };
        // This line will cause a compile error without System.Linq
        // var filtered = numbers.Where(n => n > 1);
    }
}

// Correct usage:
using System.Linq;

// Also, wrong condition example:
// var filtered = numbers.Where(n => n > 1 && n < 5 || n == 10); // Use parentheses to clarify
// Correct:
// var filtered = numbers.Where(n => (n > 1 && n < 5) || n == 10);
📊

Quick Reference

  • Purpose: Filter collections by condition.
  • Input: A collection and a lambda condition.
  • Output: A filtered IEnumerable of matching elements.
  • Namespace: System.Linq must be included.
  • Lazy evaluation: Filtering happens when you iterate the result.

Key Takeaways

Use Where to filter collections with a condition expressed as a lambda.
Remember to include using System.Linq; to access LINQ methods.
Where returns a new filtered sequence and does not change the original collection.
Use parentheses in complex conditions to avoid logic errors.
The filtering is lazy and happens when you iterate over the result.