The.NET Framework
defines lots of extension methods in the System.Linq
namespace, including Where
, Select
, SelectMany
, OrderBy
, OrderByDescending
, ThenBy
, ThenByDescending
, GroupBy
, Join
, and GroupJoin
. But remember the assembly that the namespace exists in is System.Core
.
We can use these extension methods just as we would use our own extension methods. For example, we can use the Where
extension method to get all vegetables from the Products
list, as follows:
var veges6 = products.Where(p => p.ProductName.Contains("vegetable"));
This will give us the same result as veges1
through veges5
.
As a matter of fact, the definition of the built-in LINQ extension method Where
is just like our extension method Get
, but in a different namespace:
namespace System.Linq { public static class Enumerable { public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) { if (predicate(item)) yield return item; } } } }
The statements that use LINQ extension methods are called by using the LINQ method syntax.
Unlike the other C# features that we have talked about in previous sections, these LINQ-specific extension methods are defined in .NET Framework. Therefore, to run an assembly containing any of these LINQ extension methods, you need to have .NET Framework 3.5 or above installed.