Built-in LINQ extension methods and method syntax

With Visual Studio 2008, .NET framework 3.5 defines lots of extension methods in the namespace System.Linq, including Where, Select, SelectMany, OrderBy, OrderByDescending, ThenBy, ThenByDescending, GroupBy, Join and GroupJoin.

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, like this:

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 using the LINQ method syntax.

Unlike the other C# 3.0 new features that we have talked about in previous sections, these LINQ specific extension methods are defined in .NET framework 3.5. So, to run an assembly containing any of these methods, you need .NET framework 3.5 installed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset