Sobes.tech
Junior — Middle

What approaches allow adding custom methods to LINQ and extending its functionality?

sobes.tech AI

Answer from AI

To extend LINQ functionality in C#, extension methods are usually used. These are static methods that allow adding new methods to existing types without modifying their source code.

To add a custom method to LINQ, you need to:

  1. Create a static class.
  2. In this class, define a static method with the first parameter marked with the this keyword and the type you want to extend (e.g., IEnumerable<T>).
  3. Implement the desired logic inside the method.

An example of adding an extension method that filters elements based on a condition and returns their count:

public static class LinqExtensions
{
    public static int CountIf<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        int count = 0;
        foreach (var item in source)
        {
            if (predicate(item))
                count++;
        }
        return count;
    }
}

// Usage:
var numbers = new List<int> {1, 2, 3, 4, 5};
int evenCount = numbers.CountIf(n => n % 2 == 0); // 2

Thus, extension methods allow seamless extension of LINQ by adding new operations to sequences.

What approaches allow adding custom methods to LINQ… - sobes.tech