Home > Enterprise >  Linq Aggregate function returns 0 instead of correct value
Linq Aggregate function returns 0 instead of correct value

Time:04-23

I'm trying to multiply all the values in integer array. The output of the given input array is expected to be a negative value but instead it returned as 0.

int[] nums = new int[] {41,65,14,80,20,10,55,58,24,56,28,86,96,10,3,84,4,41,13,32,42,43,83,78,82,70,15,-41};
Console.WriteLine(ArraySign(nums));
int ArraySign(int[] nums)
{
    var value= nums.Aggregate(1, (x, y) => x * y); // returns 0
    // var value= nums.Aggregate((x, y) => x * y); // returns 0
    Console.WriteLine(value);
    return value;
}

CodePudding user response:

The result of multiplying the numbers in your array exceeds the limit of primitive numeric types like int and long. Consider using BigInteger Instead:

using System.Numerics; // Remember to add reference to "System.Numerics".

BigInteger[] nums = new BigInteger[] { 41, 65, 14, 80, 20, 10, 55, 58, 24, 56, 28, 86, 96, 10, 3, 84, 4, 41, 13, 32, 42, 43, 83, 78, 82, 70, 15, -41 };
BigInteger result = nums.Aggregate((x, y) => x * y);
Console.WriteLine(result); // -4198344456762767222202786622577049600000000
  • Related