Creating your own LINQ extension methods

In Chapter 7, Implementing Interfaces and Inheriting Classes, you learned how to create your own extension methods. To create LINQ extension methods, all you must do is extend the IEnumerable<T> type.

Tip

Good Practice

Put your own extension methods in a separate class library so that they can be easily deployed as their own assembly or NuGet package.

In either Visual Studio 2017 or Visual Studio Code, open the Ch09_LinqToObjects project or folder, and add a new class file named MyLINQExtensions.cs.

Modify the class to look like the following code. Note that the ProcessSequence extension method doesn't modify the sequence because it exists only as an example. It would be up to you to process the sequence in whatever manner you want. The SummariseSequence extension method also doesn't do anything especially useful. It simply returns a long count of the number of items in the sequence using the built-in LongCount extension method. Again, it would be up to you to decide exactly what this method should do and what type it should return:

    using System.Collections.Generic; 
 
    namespace System.Linq 
    { 
      public static class MyLINQExtensions 
      { 
        // this is a chainable LINQ extension method 
        public static IEnumerable<T> ProcessSequence<T>( 
        this IEnumerable<T> sequence) 
        { 
          return sequence; 
        } 
 
        // this is a scalar LINQ extension method 
        public static long SummariseSequence<T>( 
        this IEnumerable<T> sequence) 
        { 
          return sequence.LongCount(); 
        } 
      } 
    } 

To use your LINQ extension methods, you would simply need to reference the class library assembly because the System.Linq namespace is usually already imported.

Modify the LINQ query to call your chainable extension method as follows:

    var query = names 
      .ProcessSequence() 
      .Where(name => name.Length > 4) 
      .OrderBy(name => name.Length) 
      .ThenBy(name => name); 

If you run the console application, then you will see the same output as before because your method doesn't modify the sequence. But, you now know how to extend LINQ with your own functionality.

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

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