public static class LinqExtensions
{
public static double Variance(this IList<double> data)
{
double sumSquares=0;
double avg = data.Average();
foreach (var num in data)
{
sumSquares += (num - avg * num - avg);
}
return sumSquares / (data.Count - 1);
}
public static decimal? Variance<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
{
//where to start for implementing?
}
}
I would like to make some LINQ extensions for generic types. I know how to extend LINQ without using delegates, I have several as-yet-defined types that will have properties which I will need to enumerate and things like variance out of. How can I define my Variance extension method so it takes a delegate?
Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
No. Extension methods require an instance of an object.
Of course they can; most of Linq is built around interface extension methods.
You can do like this:
public static double? Variance<TSource>(this IEnumerable<TSource> source,
Func<TSource, double> selector)
{
double sumSquares=0;
double avg = source.Average(selector);
foreach (var item in source)
{
var num = selector(item);
sumSquares += (num - avg * num - avg);
}
return sumSquares / (source.Count() - 1);
}
Here is working fiddle with that sample - http://dotnetfiddle.net/emPZC8
UPDATE
Sample of usage:
public class Item
{
public double Val {get;set;}
}
public class Program
{
public void Main()
{
var items = new List<Item>();
items.Add(new Item(){Val=1.1});
items.Add(new Item(){Val=2.1});
items.Add(new Item(){Val=3.1});
var variance = items.Variance<Item>((i) => i.Val);
Console.WriteLine(variance);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With