LINQ中的通用扩展方法

时间:2014-02-17 23:44:12

标签: 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?
        }
    }

我想为泛型类型制作一些LINQ扩展。我知道如何在不使用委托的情况下扩展LINQ,我有几个尚未定义的类型,它们将具有我需要枚举的属性以及诸如方差之类的东西。如何定义我的Variance扩展方法,以便它需要一个委托?

1 个答案:

答案 0 :(得分:8)

你可以这样做:

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);
}

以下是该示例的工作 - http://dotnetfiddle.net/emPZC8

<强>更新

使用样本:

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);
    }
}