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=?;
}
This is all freely available in MiscUtil. The
Operatorclass provides access to generic arithmetic; and there are generic implementations (as extension methods) ofSum,Average, etc – and works with any type with suitable operators in addition to the primitives. So for example, you could use Sum with ofComplex<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:
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 atdynamicin the CTP, I expect it to be a bit slower than the MiscUtil code, but we shall see.