1.5. Adding Functional Extensions for Use with LINQ
Problem
There are operations you perform on collections frequently that currently reside in utility classes. You would like to be able to have these operations be used on collections in a more seamless manner than having to pass the reference to the collection to the utility class.
Solution
Use extension methods to help achieve a more functional style of programming for your collection operations. For example, to add a weighted moving average calculation operation to numeric collections, implement a set of WeightedMovingAverage extension methods in a static class and then call them as part of those collections:
decimal[] prices = new decimal[10] { 13.5M, 17.8M, 92.3M, 0.1M, 15.7M,
19.99M, 9.08M, 6.33M, 2.1M, 14.88M };
Console.WriteLine(prices.WeightedMovingAverage());
double[] dprices = new double[10] { 13.5, 17.8, 92.3, 0.1, 15.7,
19.99, 9.08, 6.33, 2.1, 14.88 };
Console.WriteLine(dprices.WeightedMovingAverage());
float[] fprices = new float[10] { 13.5F, 17.8F, 92.3F, 0.1F, 15.7F,
19.99F, 9.08F, 6.33F, 2.1F, 14.88F };
Console.WriteLine(fprices.WeightedMovingAverage());
int[] iprices = new int[10] { 13, 17, 92, 0, 15,
19, 9, 6, 2, 14 };
Console.WriteLine(iprices.WeightedMovingAverage());
long[] lprices = new long[10] { 13, 17, 92, 0, 15,
19, 9, 6, 2, 14 };
Console.WriteLine(lprices.WeightedMovingAverage());To provide WeightedMovingAverage for the full range of numeric types, methods for both the nullable and non-nullable numeric types ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access