Further to my questions
https://stackoverflow.com/questions/10241345/any-percentage-function-in-net
https://stackoverflow.com/questions/9942202/percentage-of-each-element-in-linq
i want to create a generic extension method in .Net 4.0 which will generate percentage of the list items to the sum of the list. This list will be of Numeric types only.
My code is
public static T Percentage<T>(this T array) where T: ? // What should come in place of ?
{
double[] darray = (double[])T; // Error convert type 'T' to 'double[]'
darray = darray.Select(x=> x * 100 / darray.Sum()).ToArray();
return darray; // Error convert type 'double[]' to 'T'
}
I want to call it like
double[] MD = {8.0,21.0,25.0,13.0,26.0,37.0,37.0,33.0,71.0,9.0};
MD = MD.Percentage().ToArray();
What am i doing wrong;
You cannot constrain types by “numeric” values. It is somewhat of a limitation of the framework.
Your best best is to do this:
Essentially you need to produce an overload for each type you want to support.