Understanding LINQ behind the scenes

Now that we have a fair understanding of LINQ queries, let's consider a scenario in which we need to alter the way LINQ works. For the sake of explanation, let's consider a scenario in which we need to change the built-in implementation of the Where clause in the query.

To do that, we first need to understand how the Where clause works in LINQ queries. We can do this by looking at the definition of the Where clause in Visual Studio. The following is how the definition of the Where clause would appear:

public static IEnumerable<TSource> Where(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)

Now, to create our own implementation of the Where clause, we will need to create an extension method with the same signature.

Once this is done, we can remove the using statement for System.Linq in the respective class and, instead, use our own method. The following is the complete code in which we have altered the built-in implementation of the Where clause without its own custom implementation:

public static class LinqExtensions
{
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
foreach (TSource item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
}

Please note that in the preceding example, we have used the Yield keyword. The Yield keyword was introduced in C# in 2.0. Using this keyword, the execution will basically remember the item that was returned from the previous execution of the Where function and will return the next item in the iteration.

This is particularly important when we working using LINQ queries on data providers such as SQL. Due to the usage of Yield, the query won't be sent to the database until the result is iterated over. However, this would also mean if we execute the query multiple times, each time it will hit the database and hence have a negative effect on the performance of the system. 

In the next section, we will look at how LINQ queries are used on an XML data source.

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

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