Site Loader
Auckland, New Zealand
In our previous post we already saw some of the aggregate functions available in LINQ like Min, Max, Sum, Count etc. But there is one more important function in LINQ names Aggregate() which will perform some calculation over sequence of value. Here is the explanation provided from MSDN on Aggregate function This method works by calling func one time for each element in source. Each time func is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to func). The first element of source is used as the initial aggregate value. The result of func replaces the previous aggregated value. Aggregate returns the final result of func. Let’s understand Aggregate function with some examples Again we are going to take the same custom class (Student)
public class Student
{
    public int StudID { get; set; }
    public string Name { get; set; }
    public string Class { get; set; }
    public List Subjects { get; set; }
}
Populate some values
List students = new List()
{
    new Student { StudID = 101, Name= "Karthik", Class = "10th", Subjects = new List { "C#", "ADO.Net", "EF"}},
    new Student { StudID = 108, Name= "Karthik", Class = "10th", Subjects = new List { "C#", "ADO.Net", "EF"}},
    new Student { StudID = 104, Name = "Ram", Class = "11th", Subjects= new List{ ".Net", "C#", "SQL", "EF"}},
    new Student { StudID = 103, Name = "John", Class = "9th", Subjects= new List{ ".Net", "MVC"}},
    new Student { StudID = 106, Name = "Bill", Class = "9th", Subjects= new List{ "EF", "MVC"}},
    new Student { StudID = 109, Name = "Jacob", Class = "12th", Subjects = new List { "MVC", "Powershell" } }
};
In all our examples below we are going to perform basic operations, but here we are no where going to use the foreach loop, since Aggregate function will perform that for us (As you know Aggregate function act as a  accumulator function over a sequence.

Example 1

Get all the Students names in Reverse order
//Reverse student names with Aggregate function
string name = students.Select(x => x.Name).Aggregate((first, next) => next + " " + first);
Console.WriteLine(name);
As you can see, we have first retrieved all the names using Select clause and then used aggregate function and got passed two parameters, here the first is the aggregate value(initial value of the sequence), and the next value add the first value and becomes the first value in next sequence.

Example 2

Add all the students ID
//Add all Student ID
int result = students.Select(x => x.StudID).Aggregate((first, next) => first + next);
//Which is more equivalent to students.Select(x => x.StudID).Sum();
Console.WriteLine(result);

Example 3

Select students studying in 9th Class
//Select students studying in 9th
string studentName = students.Where(x => x.Class.Contains("9th"))
                                .Select(x => x.Name)
                                .Aggregate((first, next) => first + "," + next);
Console.WriteLine(studentName);
As you can see above, I have first selected all students by their class and then got all their name and then aggregated to get their name in sequence. Here is the complete code
public static void AggregateLINQ()
{
    List students = new List()
    {
    new Student { StudID = 101, Name= "Karthik", Class = "10th", Subjects = new List { "C#", "ADO.Net", "EF"}},
    new Student { StudID = 108, Name= "Karthik", Class = "10th", Subjects = new List { "C#", "ADO.Net", "EF"}},
    new Student { StudID = 104, Name = "Ram", Class = "11th", Subjects= new List{ ".Net", "C#", "SQL", "EF"}},
    new Student { StudID = 103, Name = "John", Class = "9th", Subjects= new List{ ".Net", "MVC"}},
    new Student { StudID = 106, Name = "Bill", Class = "9th", Subjects= new List{ "EF", "MVC"}},
    new Student { StudID = 109, Name = "Jacob", Class = "12th", Subjects = new List { "MVC", "Powershell" } }
    };

    //Reverse student names with Aggregate function
    Console.WriteLine("Reverse Student Names");
    string name = students.Select(x => x.Name).Aggregate((first, next) => next + " " + first);
    Console.WriteLine(name);

    //Add all Student ID
    Console.WriteLine("\nSUM of Student ID");
    int result = students.Select(x => x.StudID).Aggregate((first, next) => first + next);
    //Which is more equivalent to students.Select(x => x.StudID).Sum();
    Console.WriteLine(result);

    Console.WriteLine("\nSelect students studying in 9th");
    //Select students studying in 9th
    string studentName = students.Where(x => x.Class.Contains("9th"))
                                    .Select(x => x.Name)
                                    .Aggregate((first, next) => first + "," + next);
    Console.WriteLine(studentName);
}
}

Output

output6 I hope this post might have given more details on what aggregate functions are in LINQ. Please leave your comments and thanks for reading !!! Thanks, Karthik KK

Post Author: Karthik kk

2 Replies to “Aggregate Function in LINQ (Series)”

  1. Hi, I do believe this is a great web site. I stumbledupon it 😉 I may return once again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

    1. Thanks for reading the post.

      Surly I well contribute to community.

      Thanks for bookmarking though.

      Thanks
      Karthik

Leave a Reply to Samual Stove Cancel reply

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