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:
- Create a static class.
- In this class, define a static method with the first parameter marked with the
thiskeyword and the type you want to extend (e.g.,IEnumerable<T>). - 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.