Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic extension methods in LINQ

Tags:

c#

linq

generics

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?

like image 681
wootscootinboogie Avatar asked Feb 17 '14 23:02

wootscootinboogie


People also ask

What are extension methods in LINQ?

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.

What are extension methods in C#?

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.

Can you add extension methods to an existing static class?

No. Extension methods require an instance of an object.

Is it possible to achieve method extension using interface?

Of course they can; most of Linq is built around interface extension methods.


1 Answers

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);
    }
}
like image 139
Sergey Litvinov Avatar answered Nov 15 '22 17:11

Sergey Litvinov