gpt4 book ai didi

c#-3.0 - 使用lambda转换for循环(C#3.0)

转载 作者:行者123 更新时间:2023-12-02 06:24:42 25 4
gpt4 key购买 nike

如何转换下面的代码

double sumxy = 0;

for (int i = 0; i < x.Count; i++)
{sumxy = sumxy + (x[i] * y[i]);}

通过使用 lambda

我正在使用 C#3.0。 x 和 y 是双数列表

谢谢

最佳答案

如果您使用的是 .NET 4,则可以使用 Zip运算符(operator):

double sumxy = x.Zip(y, (a, b) => a * b).Sum();

或者在 .NET 3.5 中:

double sumxy = x.Select((value, index) => value * y[index]).Sum();

关于c#-3.0 - 使用lambda转换for循环(C#3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2781320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com