C# LINQ `Where()` Method: Efficient Data Filtering
Master data filtering in C# using LINQ's `Where()` method. This tutorial explains its functionality, demonstrates its use with lambda expressions, and highlights its efficiency and conciseness for creating flexible and readable data filtering operations on various collections.
Using LINQ's `Where()` Method for Data Filtering in C#
LINQ (Language Integrated Query) is a powerful feature of C# that simplifies data manipulation. The `Where()` method is a core part of LINQ, providing an efficient and expressive way to filter collections of data based on specified criteria.
Understanding LINQ's `Where()` Method
The `Where()` method is an extension method available for any collection that implements the `IEnumerable
`Where()` Method Syntax
IEnumerable<T> filteredCollection = myCollection.Where(item => condition);
The `condition` is a boolean expression evaluated for each item in `myCollection`. The `Where()` method returns a new `IEnumerable
Example: Filtering Employees by Age
using System;
using System.Collections.Generic;
using System.Linq;
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
public class WhereExample {
public static void Main(string[] args) {
List<Person> employees = GetEmployees();
var adults = employees.Where(e => e.Age >= 18); //Filter employees who are at least 18 years old.
// ... (code to print the names and ages of the adults) ...
}
// Helper method to create a list of employees
static List<Person> GetEmployees() { ... }
}
Key Advantages of `Where()`
- Readability: Makes filtering logic clear and concise, especially when using lambda expressions.
- Efficiency (Deferred Execution): Avoids unnecessary processing until the results are needed. This is beneficial when dealing with large datasets.
- Flexibility: Works with various collection types that implement `IEnumerable
`. - Composability: Can be chained with other LINQ methods for complex data transformations.