Implement the Where method in C#. Explain.

The Where method in C# is a LINQ extension method that is used to filter a sequence of elements based on a specified condition. The Where method returns a new sequence that contains only the elements from the original sequence that satisfy the provided condition.

To implement the Where method in C#, you can define it as an extension method for the IEnumerable<T> interface. Here’s an example implementation:

public static class EnumerableExtensions
{
    public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        foreach (var item in source)
        {
            if (predicate(item))
            {
                yield return item;
            }
        }
    }
}

In this implementation:

  1. The Where method is defined as an extension method for IEnumerable<T>.
  2. It takes a predicate Func<T, bool> as a parameter, which represents the condition to filter the elements.
  3. It uses a foreach loop to iterate over each element of the source sequence.
  4. The predicate function is applied to each element, and if the condition is satisfied (predicate(item) returns true), the item is yielded with the yield return statement.
  5. The method returns an IEnumerable<T> that contains only the elements that satisfy the condition.

You can then use the Where method on any collection that implements the IEnumerable<T> interface, such as arrays, lists, or other enumerable sequences. Here’s an example usage:

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var filteredNumbers = numbers.Where(n => n % 2 == 0);

foreach (var number in filteredNumbers)
{
    Console.WriteLine(number);
}

In this example, the Where method is used to filter the numbers collection and retrieve only the even numbers. The predicate n => n % 2 == 0 checks if each number is divisible by 2 without a remainder. The filtered numbers are then iterated and displayed using a foreach loop.

The implementation of the Where method demonstrates the basic concept of filtering elements based on a condition. You can further customize and extend the implementation based on your specific requirements or add additional LINQ operators to the EnumerableExtensions class.

error: Content is protected !!