linq filter list by multiple values

linq filter list by multiple values


 

Advanced Filtering of Lists by Multiple Values with LINQ in C#

Filtering collections based on multiple criteria is a common requirement in software development. LINQ (Language Integrated Query) in C# provides an elegant and powerful way to handle such tasks, allowing for concise, readable, and efficient code. This article explores how to use LINQ to filter a list by multiple values, showcasing the flexibility and power of LINQ for complex data querying.

Understanding Multi-Criteria Filtering with LINQ

LINQ allows for chaining multiple conditions within a query, making it possible to filter data sets based on multiple criteria simultaneously. This capability is especially useful when dealing with lists of objects where you need to apply several filters to pinpoint specific data.

Example: Filtering a List of Products

Consider a scenario where you have a list of Product objects, and you want to filter this list to find products that match specific size, color, and price criteria.

Step 1: Define the Product Class

 

public class Product
{
    public string Name { get; set; }
    public string Color { get; set; }
    public double Price { get; set; }
    public string Size { get; set; }
}

Step 2: Create and Populate the List

 

List<Product> products = new List<Product>
{
    new Product { Name = "T-Shirt", Color = "Red", Price = 19.99, Size = "M" },
    new Product { Name = "Jeans", Color = "Blue", Price = 39.99, Size = "L" },
    new Product { Name = "Sweater", Color = "Red", Price = 29.99, Size = "S" },
    new Product { Name = "Skirt", Color = "Blue", Price = 34.99, Size = "M" }
};

Step 3: Use LINQ to Filter the List by Multiple Values

 

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

public class Program
{
    public static void Main()
    {
        string desiredColor = "Red";
        double maxPrice = 30.00;
        string[] sizes = { "S", "M" };

        var filteredProducts = products.Where(p => p.Color == desiredColor && p.Price <= maxPrice && sizes.Contains(p.Size)).ToList();

        foreach (var product in filteredProducts)
        {
            Console.WriteLine($"{product.Name} - ${product.Price}");
        }
    }
}

In this example, products are filtered to find those that are red, cost $30 or less, and are available in sizes "S" or "M". The Contains method from System.Linq is used to check if the product's size matches any of the sizes in the sizes array, demonstrating how to filter by multiple values.

Tips for Effective Multi-Criteria Filtering

  1. Clarity: Keep the filtering logic clear and concise. If the logic becomes too complex, consider breaking it down into multiple queries or helper methods.
  2. Performance: Be aware of the performance implications of complex queries, especially with large data sets. Evaluating the most restrictive conditions first can help improve performance.
  3. Testing: Ensure to thoroughly test queries with multiple conditions to avoid logical errors that might result in incorrect filtering.

Leave a reply Your email address will not be published. Required fields are marked*

Popular Posts

Categories Clouds