Get the sum of array elements in C # using generics

I want to write a method that can take an arbitrary array of a numeric type and return the sum of all elements between startIndex and endIndex. This is what I have:

private static T SumArrayRange<T>(T[] scores, int startIndex, int endIndex)
{
    T score = 0;
    for (int i = startIndex; i <= endIndex; i++)
    {
        score += scores[i];
    }
    return score;
}

But compilation fails with these two errors.

  • It is not possible to implicitly convert the type 'int' to 'T'.
  • The operator '+ =' cannot be applied to operands of type 'T' and 'T'

Is there a way to make T be only one of the number types (long, double, etc.)? Or their more elegant way to solve this?

+3
source share
9 answers

, , . , INumeric IArithmetic , Add, Subtract .., , int long. 5- MS Connect, - . :

, .NET Framework 4.0.

:

+11

LINQ, . :

var mySum = myCollection.Skip(startIndex).Take(count).Sum();

Sum , . , , "myCollection" .

+7

, T, +=. , .NET , .

+1

.

T score = default(T)
for (int i = startIndex; i <= endIndex; i++)
{
    score += (dynamic)scores[i];
}
return score;

.

+1

, T . T HttpWebRequest, 0 + =

,

T score = default(T);

, , T , + =.

0

- , . , , !

0

, , int.Parse() ?

0

"" T ,

( , add T).

    private static Func<T, T, T> CreateAdd<T>()
    {
        Func<T, T, T> addMethod = null;
        Expression<Func<T, T, T>> addExpr = null;

        if (typeof(T) == typeof(string))
        {
            //addExpr = (Expression<Func<T, T, T>>)((a, b) => ((T)(object)((string)(object)a + (string)(object)b)));
            //addMethod = addExpr.Compile();

            addMethod = (a, b) => {
                string aa = (string)(object)a;
                string bb = (string)(object)b;

                double da;
                double db;
                double.TryParse(aa, out da);
                double.TryParse(bb, out db);
                double c = da + db;

                string res = c.ToString();

                return (T)(object)res;
            }; // End Delegate addMethod
        }
        else
        {
            ParameterExpression lhs = Expression.Parameter(typeof(T), "lhs");
            ParameterExpression rhs = Expression.Parameter(typeof(T), "rhs");

            addExpr = Expression<Func<T, T, T>>.Lambda<Func<T, T, T>>(
                Expression.Add(lhs, rhs),
               new ParameterExpression[] { lhs, rhs }
            );

            addMethod = addExpr.Compile();
        }

        return addMethod;
    }



    // MvcTools.Aggregate.Functions.Sum<T>(vals);
    public static T Sum<T>(params T[] vals)
    {
        T total = default(T);

        //Enumerable.Aggregate(vals, delegate(T left, T right) { return left + right; }); 
        Func<T, T, T> addMethod = CreateAdd<T>();

        foreach (T val in vals)
        {
            total = addMethod(total, val);
        }

        return total;
    } // End Function Sum

:

int[] vals = new int[] { 1, 2, 3, 4, 5 };
int sum = MvcTools.Aggregate.Functions.Sum<int>(vals);

double[] dvals = new double[] { 1, 2, 3, 4, 5 };
double dsum = MvcTools.Aggregate.Functions.Sum<double>(dvals);

string[] strs = new string[] { "1", "2", "3", "4", "5" };
string str = MvcTools.Aggregate.Functions.Sum<string>(strs);

: 15, 15.0, "15"

0

Source: https://habr.com/ru/post/1712910/


All Articles