Get The Sum Of Integers From An Array Of Objects Using C#

To get the sum of integers from an array of objects that contains a mix of data types (integers, floats, booleans, strings, and nulls). There are 2 ways to perform this operation.

1. Using LINQ

you can use LINQ to filter the array to only include the integer values and then use the Sum method to calculate the sum.

Example implementation:

object[] myArray = new object[] { 1, 2.5f, true, "hello", null, 3 };

int sum = myArray.OfType<int>().Sum();

Console.WriteLine(sum); // Output: 4

In the above example, an array myArray of objects containing a mix of data types, including an integer, a float, a boolean, a string, a null value, and another integer. the LINQ extension method OfType<int>() to filter the array to only include the integer values, and then use the Sum method to calculate the sum of the integers in the filtered array. The OfType method returns only the elements in the sequence that are of the specified type, in this case, integers.

2. Using Loop

Using a loop we can also Sum of integers from an array of objects that contains a mix of data types.

Example implementation:

object[] myArray = new object[] { 1, 2.5f, true, "hello", null, 3 };

object[] actualValues = (Object[]) myArray;
int sum = 0;

foreach(var item in actualValues) {
    if (item != null) {
        Type tp = item.GetType();
        if (tp.Equals(typeof(int))) {
            sum += (int) item;
        }
    }
}

Console.WriteLine("Sum of Integer Values: " + sum); // Output: 4

In the above code, a variable sum is initialized to zero. We then loop through each element in actualValues using a foreach loop. Within the loop, we check if the current element is not null using an if statement. If it is not null, we get its type using the GetType() method and store it in a variable tp. We then check if the type of the current element is int using the Equals() method and passing it the typeof(int) argument. If the type is int, we cast the current element to int using the (int) type conversion operator and add it to the Sum variable.

 

If you have an array of objects that contains multiple data types and you want to sum up the values of a specific type, you can modify the above code accordingly by replacing int with the appropriate data type.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories