在LINQ中,您可以使用Aggregate方法创建自己的自定义聚合操作。此方法使您可以对集合或序列的值执行自定义聚合操作。它不支持C#和VB.Net语言的查询语法,但可以支持两种语言的方法语法。它同时存在于Queryable和Enumerable类中。此方法以3种不同的方式重载:
- Aggregate
(IEnumerable 此方法用于在序列上应用累加器函数。指定的种子值用作初始累加器值,并且指定的函数用于选择结果值。,TAccumulate,Func ,Func ): - Aggregate
(IEnumerable 此方法在序列上应用累加器函数。指定的种子值用作初始累加器值。,TAccumulate,Func ): - Aggregate
(IEnumerable 此方法在序列上应用累加器函数。,Func ):
范例1:
// C# program to illustrate the
// use of aggregate method
using System;
using System.Linq;
class GFG {
// Main Method
static public void Main()
{
// Data source
string[] sequence = {"Geeks", "gfg",
"GeeksforGeeks", "GFG"};
// Concatenate the element of the
// given sequence using Aggregate function
var result = sequence.Aggregate((q1, q2) => q1 + "-" + q2);
Console.WriteLine(result);
}
}
Geeks-gfg-GeeksforGeeks-GFG
说明:在var结果中= sequence.Aggregate((q1,q2)=> q1 +“-” + q2); ,首先使用Geeks和gfg元素并在它们之间执行串联操作,然后使用此结果与GeeksfoGeeks元素进行串联。同样,此结果用于执行与GFG元素的连接操作,最后将最终结果存储在结果变量中。或者简单地就像: ((((Geeks-gfg)-GeeksforGeeks)-GFG)
范例2:
// C# program to find the total
// salary of the employees
using System;
using System.Linq;
using System.Collections.Generic;
// Employee details
public class Employee {
public int emp_id
{
get;
set;
}
public string emp_name
{
get;
set;
}
public string emp_gender
{
get;
set;
}
public string emp_hire_date
{
get;
set;
}
public int emp_salary
{
get;
set;
}
}
class GFG {
// Main method
static public void Main()
{
List emp = new List() {
new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female",
emp_hire_date = "12/3/2017", emp_salary = 20000},
new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female",
emp_hire_date = "22/4/2018", emp_salary = 30000},
new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male",
emp_hire_date = "3/5/2016", emp_salary = 40000},
new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female",
emp_hire_date = "4/8/2017", emp_salary = 40000},
new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male",
emp_hire_date = "12/1/2016", emp_salary = 40000},
new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female",
emp_hire_date = "17/6/2015", emp_salary = 50000},
};
// Query to find the total salary
// of the employees
// Using Aggregate method
var res = emp.Select(e => e.emp_salary).Aggregate((x,
y) => x + y);
Console.WriteLine("Total salary of the Employees: {0}", res);
}
}
Total salary of the Employees: 220000
说明:此var res中的Aggregate方法的工作= emp.Select(e => e.emp_salary).Aggregate((x,y)=> x + y);声明是:
(20000, 30000) => 20000 + 30000;
(50000, 40000) => 50000 + 40000;
(50000, 40000) => 130000 + 40000;
(130000, 40000) => 170000 + 40000;
(170000, 50000) => 170000 + 50000;
final value store in res is 220000
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.aggregate?view=netframework-4.8