Creating LINQ Extension Method

Learn about creating custom LINQ extension methods and the importance of organizing them in a separate class library for easy deployment.

To create LINQ extension methods, all we must do is extend the IEnumerable<T> type.

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

Improving the Average extension method

We will improve the Average extension method as an example. A well-educated school child will tell us that average can mean one of three things:

  • Mean: Sum the numbers and divide by the count.

  • Mode: The most common number.

  • Median: The number in the middle of the numbers when ordered.

Microsoft’s implementation of the Average extension method calculates the mean. We might want to define our own extension methods for Mode and Median:

Step 1: In the LinqWithEFCore project, add a new class file named MyLinqExtensions.cs.

Step 2: Modify the class, as shown in the following code:

Get hands-on with 1400+ tech skills courses.