C#中包含List的Lambda表达式 [英] Lambda expressions with List in C#
问题描述
请考虑这个例子,
List< int> lst = new List< int> {1,2,3,4};
int result = lst.Aggregate((x,y)=> x * y);
根据文章(x,y)指定输入参数和x * y作为实现,我的疑问是,aggregate()是列表的方法,那么它必须有内在通过它自己实现聚合,那么(x * y)指定或者更确切需要...
请提及解释lambda和单独列出的文章......
提前致谢,
Please consider this example,
List<int> lst = new List<int> { 1, 2, 3, 4 };
int result = lst.Aggregate((x, y) => x * y);
As per the articles (x,y) specifies input parameters and x*y as implementation, my doubt is, aggregate() is the method of list, then it has to have inner implementation of aggregation by its own, then what (x*y) specifies or rather needed here...
Please mention the articles explaining lambda and list separately...
Thanks in advance,
推荐答案
这里x * y
表示元素将通过乘法汇总。
参考 - C#Aggregate [ ^ ]。
参见示例及其输出。你会很清楚。
Herex * y
indicates that the elements will be aggregated by multiplication.
Refer - C# Aggregate[^].
See the examples and their outputs. You will be clear.
int[] array = { 1, 2, 3, 4, 5 };
int result = array.Aggregate((a, b) => b + a);
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15
Console.WriteLine(result);
result = array.Aggregate((a, b) => b * a);
// 1 * 2 = 2
// 2 * 3 = 6
// 6 * 4 = 24
// 24 * 5 = 120
Console.WriteLine(result);
lambda几乎只是一个没有名字的方法。在=>之前的(x,y)
部分在函数体之后指定参数和x * y
部分。
在这种情况下,你正在做的是相同的of:
A lambda is pretty much just a method without a name. The(x,y)
part before the => specifies the parameters and thex * y
part after it is the body of the function.
In this case, what you are doing is the equivalent of:
List<int> lst = new List<int> { 1, 2, 3, 4 };
int x = 0;
for (int i = 0; i < lst.Count; i ++)
{
int y = lst[i];
x = i == 0 ? y : x * y;
}
int result = x;
仅限延迟执行(暂时不要担心)。
虚假HTML结束标签删除 - OriginalGriff [/ edit]
Only with deferred execution (don't worry about that for the moment).
[edit]Spurious HTML closing tags removed - OriginalGriff[/edit]
这篇关于C#中包含List的Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!