[Solved] How to sum integer item in List?


Though the other answers supplied are effective enough, I would like to supply a thorough answer to assist at more than just the current syntactical level of C#. For example; Linq wasn’t available prior to 3.5.

IS Keyword

Checks if an object is compatible with a given type, or (starting with C# 7.0) tests an expression against a pattern.

LINQ

Many of the concepts that LINQ has introduced were originally tested in Microsoft’s research project. LINQ was released as a major part of .NET Framework 3.5 on November 19, 2007.

Primal Sum

A primitive version to do it all in one shot would be to write a method that returns a double value but accepts a List<object> value. The reason I chose double is due to it’s incredibly high maximum range of ±5 * 10^-324 – ±1.7 * 10^308. The double type is capable of achieving the sum of all values provided, and the risk for overflow is reduced, but not eliminated. Even double has a minimum and maximum value. I’ve tried to account for this; however, all I can do is let the exception bubble back up to the implementation.

public double SumNumericsFromListOfObjects(List<object> objects) {
    double sum = 0;
    foreach (object o in objects) {
        double val = 0;
        if (double.TryParse(o.ToString(), out val)
            sum += val;
    }
    return sum;
}

// Usage:
private void DoSomeCoolStuff() {
    List<object> myObjects = new List<object>();
    object[] objects = new object[] { 12, 32, 1, 9, "5", "18", 3.14, "9.9", false };
    myObjects.AddRange(objects);

    double sumOfObjects = SumNumericsFromListOfObjects(myObjects);
    int iSum = 0;
    long lSum = 0;
    if (sumOfObjects < int.MaxValue)
        iSum = (int)sumOfObjects;
    else if (sumOfObjects > int.MaxValue && sumOfObjects < long.MaxValue)
        lSum = (long)sumOfObjects;
    else
        // You just have to use the double type at this point.
}

The above example should handle most cases from the object list. Granted the original post clearly states objects of type int should be summed and doesn’t really specify whether string values or double values should be accounted for, nor how they should be handled. I personally believe that it would be best to handle all cases; therefore, since string values can be parsed to double values if they meet certain criteria and doubles can be converted back to integers (assuming their values do not exceed the max value for int), I decided to sum at the double level and then convert back to integer at the implementation of the method to ensure no numeric values are missed. The above method should be able to handle the following types:

byte: 0 – 255

sbyte: -128 – 127

short: -32768 – 32767

ushort: 0 – 65535

int: -2147483648 – 2147483647

uint: 0 – 4294967295

long: -9 * 10^18 – 9 * 10^18

ulong: 0 – 1.8 * 10^19

float: ±1.5 * 10^-45 – ±3.4 * 10^38

double: ±5 * 10^-324 – ±1.7 * 10^308

decimal: ±10^-28 – ±7.9 * 10^28

Extension Methods

Another quick and efficient route if you find yourself frequently adding up values from a list of objects would be to add extension methods to the List<object> type. Keep in mind, this method also has the potential to overflow the minimum and maximum values for the type the arithmetic is being performed on.

internal class Extensions {
    public static double Sum(this List<object> objects) {
        double sum = 0;
        foreach (object o in objects) {
            double val = 0;
            if (double.TryParse(o.ToString(), out val))
                sum += val;
        }
        return sum;
    }
}

// Usage:
double sum = myObjects.Sum();

If anyone feels I left out some useful information, or maybe did something incorrectly here, please feel free to comment and inform me so that I can update this post to better educate future readers.

0

solved How to sum integer item in List?