Using the Where Operator in LINQ: Filtering Collections

The Where operator in LINQ is like a filter for a collection (like an array, list, or other enumerable data). It allows you to selectively pick elements from the collection based on a certain condition. Think of it as a way to "query" the collection to get only the items that meet a specific criterion.

Scenario: Imagine you're a manager at a retail store, and you want to find all the products in your inventory that are currently out of stock (have a quantity of 0).

Scenario:  You're a content manager for a social media platform, and you want to find all the posts that have received more than 100 likes for further promotion.

A simple breakdown how the Where operator works:

  • Collection: You start with a collection of items (e.g., a list of numbers, names, or objects).
  • Condition: You specify a condition that you want the items to satisfy. This condition is expressed using a lambda expression, which is like a short piece of code that checks each item.
  • Filtering: The Where operator goes through each item in the collection and checks if the condition is true for that item. If the condition is true, the item is included in the result; if not, it's excluded.
  • Result: The Where operator returns a new collection containing only the items that passed the condition.

A program that Filter List and Display details of employees who have joined within the last year.

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

class Program
{
    static void Main(string[] args)
    {
        // Create a list of employees with their details
        List<Employee> employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "John", IsActive = true, JoinDate = new DateTime(2023, 1, 15) },
            new Employee { Id = 2, Name = "Jane", IsActive = true, JoinDate = new DateTime(2022, 8, 10) },
            new Employee { Id = 3, Name = "Alex", IsActive = false, JoinDate = new DateTime(2021, 5, 5) },
            new Employee { Id = 4, Name = "Emily", IsActive = true, JoinDate = new DateTime(2023, 3, 25) },
            new Employee { Id = 5, Name = "Mike", IsActive = false, JoinDate = new DateTime(2022, 8, 5) }
        };

        // Filter and retrieve employees who have joined within the last year
        var recentEmployees = employees
            .Where(emp => emp.JoinDate >= DateTime.Now.AddYears(-1))
            .ToList();
  Console.WriteLine("Employees Joined in last one year");
        Console.WriteLine("---------------------------------");
        // Display details of recent employees
        foreach (var employee in recentEmployees)
        {
            Console.WriteLine($"ID: {employee.Id}, Name: {employee.Name}, Join Date: {employee.JoinDate}");
        }
    }
}

class Employee
{
    // Properties representing employee details
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsActive { get; set; }
    public DateTime JoinDate { get; set; }
}


--Output Result

Employees Joined in last one year
---------------------------------
ID: 1, Name: John, Join Date: 15-01-2023 00:00:00
ID: 2, Name: Jane, Join Date: 10-08-2022 00:00:00
ID: 4, Name: Emily, Join Date: 25-03-2023 00:00:00

A program that filters a dictionary of books based on their genres.

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

class Book
{
    public string? Title { get; set; }
    public string? Author { get; set; }
    public string? Genre { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Create a dictionary representing a library of books
        Dictionary<string, Book> library = new Dictionary<string, Book>
        {
            { "The Great Gatsby", new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", Genre = "Classic" } },
            { "To Kill a Mockingbird", new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", Genre = "Fiction" } },
            { "1984", new Book { Title = "1984", Author = "George Orwell", Genre = "Dystopian" } },
            { "Pride and Prejudice", new Book { Title = "Pride and Prejudice", Author = "Jane Austen", Genre = "Romance" } },
            { "The Hobbit", new Book { Title = "The Hobbit", Author = "J.R.R. Tolkien", Genre = "Fantasy" } }
        };

        // Using the Where operator to filter books by genre
        string targetGenre = "Fantasy";
        var fantasyBooks = library.Where(book => book.Value.Genre == targetGenre);

        // Display books in the specified genre
        Console.WriteLine($"Books in the {targetGenre} Genre:");
        Console.WriteLine("----------------------------");

        foreach (var book in fantasyBooks)
        {
            Console.WriteLine($"Title: {book.Value.Title}, Author: {book.Value.Author}");
        }
    }
}

--Output
Books in the Fantasy Genre:
----------------------------
Title: The Hobbit, Author: J.R.R. Tolkien

A program that demonstrates how to use the Where operator with both an array and a list to filter products based on their prices:

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

class Program
{
    static void Main(string[] args)
    {
        // Creating an array of products
        Product[] productsArray = new Product[]
        {
            new Product { Name = "Laptop", Price = 1000 },
            new Product { Name = "Phone", Price = 800 },
            new Product { Name = "Tablet", Price = 500 },
            new Product { Name = "Monitor", Price = 300 },
            new Product { Name = "Keyboard", Price = 50 }
        };

        // Creating a list of products
        List<Product> productsList = new List<Product>
        {
            new Product { Name = "Headphones", Price = 100 },
            new Product { Name = "Mouse", Price = 30 },
            new Product { Name = "Speaker", Price = 150 }
        };

        decimal maxPrice = 200;

        // Using the Where operator to filter products based on price in the array
        var affordableProductsArray = productsArray.Where(product => product.Price <= maxPrice);

        // Using the Where operator to filter products based on price in the list
        var affordableProductsList = productsList.Where(product => product.Price <= maxPrice);

        // Display affordable products from the array
        Console.WriteLine("Affordable Products (Array):");
        foreach (var product in affordableProductsArray)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }

        // Display affordable products from the list
        Console.WriteLine("\nAffordable Products (List):");
        foreach (var product in affordableProductsList)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }
    }
}

class Product
{
    public string? Name { get; set; }
    public decimal Price { get; set; }
}

--Output

Affordable Products (Array):
Name: Keyboard, Price: 50

Affordable Products (List):
Name: Headphones, Price: 100
Name: Mouse, Price: 30
Name: Speaker, Price: 150

A Program that demonstrates how to use the Where operator to filter ArrayList Store orders Data based on their total amount:

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

class Program
{
    static void Main(string[] args)
    {
        // Creating an ArrayList to store orders
        ArrayList orders = new ArrayList
        {
            new Order { OrderNumber = 101, TotalAmount = 150.25M },
            new Order { OrderNumber = 102, TotalAmount = 300.50M },
            new Order { OrderNumber = 103, TotalAmount = 75.00M },
            new Order { OrderNumber = 104, TotalAmount = 500.00M },
            new Order { OrderNumber = 105, TotalAmount = 250.75M }
        };

        // Minimum total amount for high-value orders
        decimal minimumAmount = 200.00M;

        // Using the Where operator to filter orders based on total amount
        var highValueOrders = orders.Cast<Order>().Where(order => order.TotalAmount >= minimumAmount);

        // Display high-value orders
        Console.WriteLine($"High-Value Orders (Total Amount >= {minimumAmount}");
        foreach (var order in highValueOrders)
        {
            Console.WriteLine($"Order Number: {order.OrderNumber}, Total Amount: {order.TotalAmount}");
        }
    }
}

class Order
{
    public int OrderNumber { get; set; }
    public decimal TotalAmount { get; set; }
}


--Output
High-Value Orders (Total Amount >= 200.00
Order Number: 102, Total Amount: 300.50
Order Number: 104, Total Amount: 500.00
Order Number: 105, Total Amount: 250.75

Advantages of Using the Where Operator:

  • Simplicity: The Where operator simplifies the process of filtering data from a collection based on a condition, reducing the need for manual loops and comparisons.
  • Readability: LINQ queries, including the Where operator, enhance code readability and maintainability by expressing filtering logic in a concise and declarative manner.
  • Efficiency: LINQ operators are optimized and provide efficient querying of data, which can lead to better performance.
  • Reusability: LINQ operators can be easily reused for various filtering scenarios across different types of collections.

Let's compare the Where operator with a manual filtering approach using a for loop:

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 is a powerful tool that simplifies data filtering and manipulation in LINQ, making code more expressive and efficient. It is widely used to extract relevant data from collections based on specific criteria, contributing to cleaner and more maintainable code.

If you encounter any issues or have further questions, feel free to let me know, and I'll be glad to assist!

Thank you for reading, and I hope this post has helped provide you with a better understanding of about Using `Where` Operator with List,Dictionary,Array and ArrayList. 

"Keep coding, keep innovating, and keep pushing the boundaries of what's possible!

Happy Coding !!!