Using LINQ's Where() Method with a Custom Method as a Condition in C#

Learn how to use LINQ's `Where()` method in C# with a custom method as the filtering condition. This tutorial provides code examples demonstrating this technique, enhancing your LINQ skills and showcasing its flexibility in data manipulation.



Using LINQ's `Where()` Method with a Custom Method as a Condition

This article demonstrates using LINQ (Language Integrated Query) in C# to filter a collection based on a custom method. LINQ provides a powerful and readable way to query and manipulate data in C#.

Understanding LINQ's `Where()` Method

LINQ's `Where()` method filters a sequence of values, returning only those that satisfy a specified condition. The condition is typically provided as a lambda expression or a method.

Creating a Custom Filtering Method

In this example, we create a custom method (`checkstring`) to determine if a string's length is less than 3 characters. This method will be used as a condition within the LINQ `Where()` method.


static bool checkstring(string str) {
    return str.Length < 3;
}

Example: Filtering Employee Names


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

public class LinqExample {
    public static void Main(string[] args) {
        // ... (code to create a list of employee names and filter names using Where() with checkstring) ...
    }

    // ... (checkstring method) ...
}

Explanation

The `Main` method creates a list of employee names. The `Where()` method, along with a lambda expression, applies the `checkstring` method to filter the list. Only names with less than 3 characters are selected and printed to the console.