在LINQ中,聚合函数是用于从值的集合中计算单个值的那些函数。聚合函数的现实示例是根据全年收集的读数来计算2018年发生的年降雨量。另一个示例,sum函数用于查找给定数组或序列中存在的值的总和。
以下是用于执行聚合操作的方法的列表:
Method | Description |
---|---|
Aggregate | It performs, a custom aggregation operation on the values of a collection. |
Average | It calculates the average value of a collection of values. |
Count | It counts the elements in a collection, optionally only those elements that satisfy a predicate function. |
LongCount | It counts the elements in a large collection, optionally only those elements that satisfy a predicate function. |
Max | It determines the maximum value in a collection. |
Min | It determines the minimum value in a collection. |
Sum | It calculates the sum of the values in a collection. |
范例1:
// C# program to illustrate how to
// find the sum of the given sequence
using System;
using System.Linq;
public class GFG {
// Main Method
static public void Main()
{
int[] sequence = {20, 40, 50, 68, 90,
89, 99, 9, 57, 69};
Console.WriteLine("The sum of the given sequence is: ");
// Finding sum of the given sequence
// Using Sum function
int result = sequence.Sum();
Console.WriteLine(result);
}
}
输出:
The sum of the given sequence is:
591
范例2:
// C# program to illustrate how to
// find the minimum and maximum value
// from the given sequence
using System;
using System.Linq;
public class GFG {
// Main Method
static public void Main()
{
int[] sequence = {201, 39, 50, 9, 7, 99};
// Display the Sequence
Console.WriteLine("Sequence is: ");
foreach(int s in sequence)
{
Console.WriteLine(s);
}
// Finding the minimum value
// from the given sequence
// Using Min function
int result1 = sequence.Min();
Console.WriteLine("Minimum Value is: {0}", result1);
// Finding the maximum value
// from the given sequence
// Using Max function
int result2 = sequence.Max();
Console.WriteLine("Maximum Value is: {0}", result2);
}
}
输出:
Sequence is:
201
39
50
9
7
99
Minimum Value is: 7
Maximum Value is: 201
参考:
- https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/aggregation-operations