C# - Sum of Array Elements Using Queryable.Sum()

Here, we are going to learn how to find the sum of array elements using the predefine Sum() method of Queryable class in C#?
Submitted by Nidhi, on August 27, 2020 [Last updated : March 19, 2023]

Here we will create an array of integers and then we find the sum of all array elements using a predefine Sum() method of Quaryable class. To use a Queryable class, we need to import the System.Linq method in our program.

C# program to find the sum of array elements using Queryable.Sum()

The source code to find the sum of array elements using the predefine method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to find the sum of array element 
//using Sum() method of Queryable class.

using System;
using System.Linq;

class Sample
{
    static void Main()
    {
        int[] MyArray = { 40, 30, 20, 10, 50 };
        int sum = 0;
        
        sum = Queryable.Sum(MyArray.AsQueryable());

        Console.WriteLine("Sum of array elements: {0}", sum);
    }
}

Output

Sum of array elements: 150
Press any key to continue . . .

Explanation

In the above program, we created an array of integers. Then find the sum of all array elements using the Sum() method of Queryable class. The Sum() method returns an integer value. To use a Queryable class, we need to import the System.Linq method in our program.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.