Filtering Collections in LINQ
By FoxLearn 2/25/2025 2:40:22 AM 17
You are working with a music streaming platform, and you want to find all the songs that are from a specific genre, say "Rock", for a playlist.
A simple breakdown of how the Where operator works:
- Collection: Start with a collection (list, array, etc.) containing items you want to filter.
- Condition: Define a condition, often using a lambda expression, which checks each item for a specific criteria.
- Filtering: The Where operator filters through the collection, checking each item against the condition. Items that meet the condition are included in the result.
- Result: The operator returns a new collection, which contains only the items that satisfy the condition.
Example: Filtering Songs by Genre
Here’s a C# program that filters a collection of songs based on their genre:
using System; using System.Collections.Generic; using System.Linq; class Song { public string? Title { get; set; } public string? Artist { get; set; } public string? Genre { get; set; } } class Program { static void Main(string[] args) { // Create a list of songs List<Song> songs = new List<Song> { new Song { Title = "Bohemian Rhapsody", Artist = "Queen", Genre = "Rock" }, new Song { Title = "Shape of You", Artist = "Ed Sheeran", Genre = "Pop" }, new Song { Title = "Hotel California", Artist = "Eagles", Genre = "Rock" }, new Song { Title = "Blinding Lights", Artist = "The Weeknd", Genre = "Pop" }, new Song { Title = "Smells Like Teen Spirit", Artist = "Nirvana", Genre = "Rock" } }; // Filter and retrieve songs of the 'Rock' genre string targetGenre = "Rock"; var rockSongs = songs.Where(song => song.Genre == targetGenre).ToList(); // Display songs in the 'Rock' genre Console.WriteLine($"Songs in the {targetGenre} Genre:"); Console.WriteLine("----------------------------"); foreach (var song in rockSongs) { Console.WriteLine($"Title: {song.Title}, Artist: {song.Artist}"); } } }
Output:
Songs in the Rock Genre: ---------------------------- Title: Bohemian Rhapsody, Artist: Queen Title: Hotel California, Artist: Eagles Title: Smells Like Teen Spirit, Artist: Nirvana
Example: Filtering Products by Rating
Here’s another example, this time filtering products based on their customer rating. Imagine you’re working in an e-commerce platform and want to find all products with a rating of 4.5 stars or higher.
using System; using System.Collections.Generic; using System.Linq; class Product { public string? Name { get; set; } public decimal Price { get; set; } public double Rating { get; set; } } class Program { static void Main(string[] args) { // Create a list of products List<Product> products = new List<Product> { new Product { Name = "Smartphone", Price = 699.99, Rating = 4.7 }, new Product { Name = "Laptop", Price = 999.99, Rating = 4.5 }, new Product { Name = "Headphones", Price = 199.99, Rating = 3.8 }, new Product { Name = "Smartwatch", Price = 249.99, Rating = 4.9 }, new Product { Name = "Tablet", Price = 399.99, Rating = 4.2 } }; // Filter and retrieve products with a rating of 4.5 or higher var topRatedProducts = products.Where(product => product.Rating >= 4.5).ToList(); // Display top-rated products Console.WriteLine("Top-Rated Products (Rating >= 4.5):"); Console.WriteLine("------------------------------------"); foreach (var product in topRatedProducts) { Console.WriteLine($"Name: {product.Name}, Rating: {product.Rating}"); } } }
Output:
Top-Rated Products (Rating >= 4.5): ------------------------------------ Name: Smartphone, Rating: 4.7 Name: Laptop, Rating: 4.5 Name: Smartwatch, Rating: 4.9
Advantages of Using the Where Operator:
- Simplicity: The Where operator simplifies filtering by abstracting away manual loops and comparisons.
- Readability: LINQ queries, such as the Where operator, make code more readable and easier to maintain by expressing the filtering logic clearly.
- Efficiency: LINQ queries are optimized for performance, making them an efficient way to filter large collections.
- Reusability: You can reuse the Where operator across different collections and scenarios, making it versatile.
Comparing the Where Operator with Manual Filtering:
Using the Where Operator:
var filteredItems = collection.Where(item => condition);
Manual Filtering with a for Loop:
List<T> filteredItems = new List<T>(); foreach (var item in collection) { if (condition) { filteredItems.Add(item); } }
In summary, the Where operator in LINQ is a powerful tool that simplifies the process of filtering data. Whether you're working with a list, dictionary, or array, it allows you to query and retrieve only the items that meet your criteria, making your code cleaner, more efficient, and easier to maintain.
- Element Operators in LINQ
- Inner Join Using LINQ And Lambda
- Understanding Single, SingleOrDefault, First, and FirstOrDefault in LINQ
- Creating Dynamic LINQ Queries in C# with Predicate Builder
- How to Use Select and SelectMany Effectively in LINQ
- Optimizing LINQ: Best Practices and Tips
- Right Join in C# LINQ
- How to group by multiple columns using LINQ