Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - How to Implement Generic Method to do Math calculations on different value types

I have a method that accepts an IEnumerable-decimals and performance various math functions. I want to use the same method on an IEnumerable-int-. How do I implement this? For example to find a simple sum?

void Calculate<T>(IEnumerable <T> ListOFNumbers)
{
   int count= ListofNumbers.Count();
   ?sum=?;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is all freely available in MiscUtil. The Operator class provides access to generic arithmetic; and there are generic implementations (as extension methods) of Sum, Average, etc - and works with any type with suitable operators in addition to the primitives. So for example, you could use Sum with of Complex<T>, etc.

Note that it currently uses .NET 3.5; I did have a 2.0 version somewhere, but it isn't as tested....

A simplified example of sum is shown in the usage document:

public static T Sum<T>(this IEnumerable<T> source)
{
    T sum = Operator<T>.Zero;
    foreach (T value in source)
    {
        if (value != null)
        {
            sum = Operator.Add(sum, value);
        }
    }
    return sum;
}

Although IIRC the actual implementation has a bit more...

As an aside, note that dynamic (in .NET 4.0 / C# 4.0) supposedly supports operators, but we'll have to wait for the beta to see what it does. From my previous looks at dynamic in the CTP, I expect it to be a bit slower than the MiscUtil code, but we shall see.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...