C# - Example of LINQ Aggregate() Method

Learn about the Linq Aggregate() method and its C# implementation. By Nidhi Last updated : April 01, 2023

Here, we will create an array of strings for courses, and concatenate comma ", " between all courses and then combined all courses using Linq Aggregate() method.

C# program to demonstrate the example of LINQ Aggregate() method

The source code to demonstrate Linq Aggregate() method, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to demonstrate Linq Aggregate() method.

using System;
using System.Linq;

class LinqDemo
{
    static void Main(string[] args)
    {
        string[] Courses = { "BCA", "MCA", "MBA", "MA", "CA", "BBA" };

        string rstString = "";
        
        rstString=Courses.Aggregate((s1, s2) => s1 + ", " + s2);

        Console.WriteLine(rstString);
    }
}

Output

BCA, MCA, MBA, MA, CA, BBA
Press any key to continue . . .

Explanation

In the above program, we created an array of strings that contains courses. And then use the Aggregate() method to combine all courses and separate all courses using comma (,) operator in the final string. Here Aggregate() method will return a combined single string.

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

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





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