Suppose I have an extension method
public static IEnumerable<Product> Filter(
this IEnumerable<Product> productEnum,
Func<Product, bool> selectorParam)
{
return productEnum.Where(selectorParam);
}
which I call like so
Func<Product, bool> languageFilter = prod => prod.Language == lang;
Which if im not misaken is functionally the same as
var products = Products.Where(q => q.Language == parameter);
I’m trying to understand when one might utilize an extension method as per the 1st sample, and when to use the linq syntax.
I think you are confusing some terminology. The
Filtermethod you show is an extension method (indicated as such by thethiskeyword in the parameter list. What you are terming as “linq syntax” is actually a lambda expression.All of the LINQ methods are implemented as extension methods and support two “styles” of calling:
Actually call the extension method directly as if they were part of the type being extended. This is what you show when calling it as
productEnum.Where(selectorParam).Using a more SQL-like syntax, called LINQ query syntax. Keep in mind that this SQL-like syntax is translated by the compiler to actually call the extension methods.
When you define
Func<Product, bool> languageFilter = prod => prod.Language == lang;, you are actually defining a lambda expression and assigning it to a variable (languageFilter) of typeFunc<Product, bool>. TheProducts.Where(q => q.Language == parameter);statement is exactly the same except that rather than capturing the lambda expression in a variable you simply pass it to the extension method.For your example, to get the same result using the LINQ query syntax you would write it similar to
(assuming that parameter is defined elsewhere)