开发者

Extension Method on IEnumerable

What is the solution for writing extension method dor IEumerable which resurns for example sum of squarea of elemetns

for example for:

IList<double> L = new List<double>();
L.Add(1);
开发者_StackOverflowL.Add(2);
L.Add(3);

var result = L.MyMethod();

expected value of result is 1*1 + 2*2 + 3*3 = 14


You don't need an extension method. You can just say

var sumOfSquares = list.Sum(x => x * x);

Obviously you can make it an extension method with

public static class EnumerableDoubleExtensions {
    public static double SumSquares(this IEnumerable<double> source) {
        Contract.Requires(source != null);
        return source.Sum(x => x * x);
     }
}

To do product you just say

list.Aggregate(1d, (p, x) => p * x);

which you can easily make an extension method via

public static class EnumerableDoubleExtensions {
    public static double Product(this IEnumerable<double> source) {
        Contract.Requires(source != null);
        return source.Aggregate(1d, (p, x) => p * x);
     }
}

Note that this uses Enumerable.Aggregate of which Enumerable.Sum is a special case.


The easiest way would be to use the overload of Enumerable.Sum that sums up a sequence of projected values from a sequence:

public static double GetSumOfSquares(this IEnumerable<double> numbers)
{
    if(numbers == null)
       throw new ArgumentNullException("numbers");

    return numbers.Sum(x => x * x);
}

Do note that this will return 0D for an empty sequence. This is similar to:

numbers.Select(x => x * x)
       .Sum();

As for your question about multiplying them, you could use Enumerable.Aggregate, which is a more general operator for performing accumulation-operations on sequences:

double product = numbers.Aggregate((productSoFar, next) => productSoFar * next);

This will throw an InvalidOperationException if the sequence is empty. If you would like to return something else in this case, use the overload that accepts an initial seed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜