Junior — Middle
How have you used extensions in LINQ to add functionality?
sobes.tech AI
Answer from AI
In LINQ, extensions are usually implemented through extension methods for the interfaces IEnumerable<T> or IQueryable<T>. This allows adding new methods that appear as built-in LINQ methods, extending functionality without modifying the original code.
For example, you can create an extension method for filtering elements based on a complex condition:
public static class LinqExtensions
{
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
}
Usage:
var numbers = new List<int> {1, 2, 3, 4, 5};
bool filterEven = true;
var result = numbers.WhereIf(filterEven, n => n % 2 == 0);
Thus, extensions allow creating convenient, reusable methods for LINQ queries.