Creating your own LINQ extension methods
In Chapter 6, 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.
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.
We will look at the Average
extension method as an example. Any school child will tell you 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
.
- In the
LinqWithEFCore
project, add a new class file namedMyLinqExtensions.cs
. - Modify the class, as shown in...