Updated April 6, 2023
Introduction to LINQ Aggregate
LINQ Aggregate method can create its own custom aggregation operation on values of sequence or collections of items. Aggregate function requires assembling the values together of several rows as input and it returns a single value as a result. LINQ Aggregate function execution starts from the first value and second value and then it carries forward the result for the further operation it takes the last result as the first value and third value and then it carries forward and so on. Aggregate methods we can derive from the namespace System. Linq and the method available in both the classes Queryable and Enumerable.
Syntax:
LINQ Aggregate methods have three overloaded methods, it performs an accumulation operation. Let’s see the following syntax of aggregate extension method,
public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func);
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);
public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector);
How Aggregate works in LINQ?
LINQ Aggregate functions result in a single value. LINQ Aggregate function execution starts from the first value and second value and then it carries forward the result for the further operation it takes the last result as the first value and third value and then it carries forward and so on. The aggregate method only supports Method Syntax and it does not support query syntax. Aggregate method available in both classes Queryable and Enumerable. It is an extension method from the namespace System.Linq. Let’s see the following example which describes the working flow of aggregate function,
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LinqAggregate
{
class Program
{
static void Main(string[] args)
{
//Using Aggregate Method to show the seperation of result by use by Comma,
string[] Skill_Set = {"MVC","EntityFramework","Sqlserver","Asp.net","Linq",
"C#.net", "Web-Api","Jquery"};
var Seperated_Result = Skill_Set.Aggregate((string_1, string_2) => string_1 + "," + string_2);
Console.WriteLine("\nLINQ Aggregate - Using Seperator-Comma : \n\n" + Seperated_Result);
Console.ReadLine();
}
}
}
This program it uses the function Aggregate((string_1, string_2), this method applies the accumulator function in the collection. The particular seed value is the initial accumulator value and that particular function selects the resultant value.
var Seperated_Result = Skill_Set.Aggregate((string_1, string_2) => string_1 + "," + string_2);
Let’s see the debugging process to understand the working flow of aggregate function,
Initially it contains a null value as shown below,
Here we concatenating the items of Skill_Set in a separated string as follows,
Finally, it concatenates all the strings with a comma separator,
Output:
Examples
Aggregate function requires assembling the values together of several rows as input and it returns a single value as a result. Aggregate function is an extension method from the namespace System. Linq. Let’s see the following example programmatically,
Example #1
Code:
In this program, it shows the Aggregate Method – Seed Value the method used to add the user’s age in the collection of items. In the second overloaded function the aggregate method takes the first argument as the seed value to accumulate and the second argument as the Function type delegate, let’s see the example programmatically which use the seed parameter as shown below,
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LinqAggregate
{
class Program
{
public class UserClass
{
public string userName { get; set; }
public int userAge { get; set; }
static void Main(string[] args)
{
var get_UserAge = new List<UserClass>()
{
new UserClass { userName = "Smith", userAge = 23 },
new UserClass { userName = "Rio", userAge = 30},
new UserClass { userName = "Jack", userAge = 41},
new UserClass { userName = "Danial", userAge = 25 },
new UserClass { userName = "Peter", userAge = 32 },
};
int get_SumOf_UserAge = get_UserAge.Aggregate<UserClass, int>(0, (get_totalAge, user) => get_totalAge += user.userAge);
Console.WriteLine("\nAggregate Method - Seed Value");
Console.WriteLine("\nSum of Users- Age in the List:");
Console.WriteLine("\n"+get_SumOf_UserAge);
Console.ReadLine();
}
}
}
}
In this above program, the aggregate method is used to add the user’s age in the collection of items. In the second overloaded function the aggregate method takes the first argument as the seed value to accumulate and the second argument as the Function type delegate, let’s see the example programmatically which use the seed parameter as shown below,
int get_SumOf_UserAge = get_UserAge.Aggregate<UserClass, int>(0, (get_totalAge, user) => get_totalAge += user.userAge);
Output:
Example #2
Code:
In this program explained with the third overloaded method in which the third argument is the result selector of Func delegate expression, we need to get the result from this lets see the following program as syntax follows,
public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LinqAggregate
{
class Program
{
public class UserClass
{
public string userName { get; set; }
public int userAge { get; set; }
static void Main(string[] args)
{
var get_User = new List<UserClass>()
{
new UserClass { userName = "Smith", userAge = 23 },
new UserClass { userName = "Rio", userAge = 30},
new UserClass { userName = "Jack", userAge = 41},
new UserClass { userName = "Danial", userAge = 25 },
new UserClass { userName = "Peter", userAge = 32 },
};
// String.Empty - lambda expression as str, displays result of seed value
//and removes the last appears comma in the selector
string seperated_UserName = get_User.Aggregate<UserClass, string, string>(
String.Empty,
(str, user) => str += user.userName + ",",
str => str.Substring(0, str.Length - 1));
Console.WriteLine("\nAggregate Method with Result Selector");
Console.WriteLine("\n" + seperated_UserName);
Console.ReadLine();
}
}
}
}
string seperated_UserName = get_User.Aggregate<UserClass, string, string>( String.Empty, (str, user) => str += user.userName + ",", str => str.Substring(0, str.Length - 1));
In the above program, we described the lambda expression as str.Substring(0, str. Length – 1)); it eliminate the last appeared comma in the resultant string. Let’s see the following output below,
Output:
Conclusion
In LINQ Aggregate() method there are various methods to target our program, which helps to create our own code in a customizable way. Hope the article is helpful to understand the necessity and usage of Aggregate Method by seeing the above examples programmatically.
Recommended Articles
This is a guide to LINQ Aggregate. Here we discuss the Introduction, syntax, How aggregate works in LINQ? examples with code implementation. You may also have a look at the following articles to learn more –