LINQ版本,用于计算数组中相邻元素的和积 [英] LINQ version of calculating sum product of adjacent elements in an array
问题描述
我正在寻找一种在LINQ中执行以下操作的方法(它基本上是一个sumproduct,其中同一数组包含 n
和 n + 1
索引,显然数组长度始终为 2 * n
).
I am looking for a way to do the following in LINQ (it is basically a sumproduct where the same array contains both operands of the product at n
and n + 1
indices, obviously the array length is always 2 * n
).
int[] input = { -3, 26, -2, 19, 2, 19, 3, 29, 1, 48 };
// sum product
double result = 0;
for (int i = 0; i < input.Length; i += 2)
result += input[i] * input[i + 1];
// result = 57
// linq version of calculating resultPrice ???
如何使用LINQ做到这一点(优雅)?
How can I do this (elegantly) with LINQ?
推荐答案
var result = Enumerable.Range(0, input.Length/2)
.Select(i => input[i*2] * input[i*2 + 1]).Sum();
这应该足够了.以下是 dotNetFiddle 中的示例.
This should be enough. Here example in dotNetFiddle.
此代码几乎是以下内容的镜像:
This code is pretty much mirror of:
for (int i = 0; i < input.Length/2; i++)
result += input[i*2] * input[i*2 + 1];
与循环完全相同,但是没有循环的步骤 +2
,而是具有步骤 +1
和循环持续时间 ArrayItems/2
,然后从 input [i * 2] * input [i * 2 + 1]
which is doing the exact same thing as your loop, but instead of step +2
of your loop you have step +1
and loop duration ArrayItems/2
and you make sum of elements from input[i*2] * input[i*2 + 1]
这篇关于LINQ版本,用于计算数组中相邻元素的和积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!