C# program to calculate the sum of array elements using the Linq Aggregate() method

Here, we are going to learn how to calculate the sum of array elements using the Linq Aggregate() method in C#?
Submitted by Nidhi, on August 31, 2020

Here we will create an array of integer elements and then calculate the sum all array elements using Linq  Aggregate() method.

Program:

The source code to calculate the sum of array elements using the Aggregate() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the sum of array elements 
//using the Linq Aggregate() method.

using System;
using System.Linq;

class LinqDemo
{
    static void Main(string[] args)
    {
        int[] values = { 10, 8, 2, 2, 7, 4};
        int sum = 0;
        
        sum = values.Aggregate((val1, val2) => val1 + val2);
        
        Console.WriteLine("Sum is : "+sum);
    }
}

Output:

Sum is : 33
Press any key to continue . . .

Explanation:

In the above program, we created LinqDemo class that contains the Main() method. In the Main() method we created an array of integers and then calculate the sum of all array elements using the Aggregate() method and then print the sum on the console screen. 

To use the Aggregate() method, it is mandatory to import "System.Linq" namespace.

C# LINQ Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.