简体   繁体   English

IList 的百分比变化<t>返回 IList<t> 使用 LINQ</t></t>

[英]Percent change of a IList<T> returning IList<T> using LINQ

Given a List<T> where T is f loat/decimal/double , using LINQ, compute the percent change of all the values.给定一个List<T> ,其中T是 float loat/decimal/double ,使用 LINQ,计算所有值的percent change

This is the definition of PercentChange (without error checking for example if a is zero )这是PercentChange的定义(没有error检查,例如a是否zero

static double PercentChange(double a, double b)
{
    double result = 0;
    result = (b - a) / a;
 
    return result;
}

var list = new List<double>();
list.Add(2.0);
list.Add(2.5);
list.Add(2.0);
list.Add(1.75);

Then using LINQ would return a new List one element less, with values:然后使用LINQ将返回一个少一个元素的新列表,其值:

[.25, -.20, -.125] 

I know I can loop .我知道我可以loop I would like a functional version using LINQ .我想要一个使用LINQfunctional版本。

I'm not sure I'd find this approach more readable than a loop, but the LINQ approach would be:我不确定我会发现这种方法比循环更具可读性,但 LINQ 方法是:

list.Zip(list.Skip(1), PercentChange)

Outputs:输出:

[.25, -.2, -.125] [.25, -.2, -.125]

The idea is to take the first list, "zip" it with itself, but skip the first element (so y is the next element) and apply your PercentChange function on it.这个想法是获取第一个列表,将其自身“压缩”,但跳过第一个元素(因此y是下一个元素)并在其上应用PercentChange function。 Zip will automatically truncate the resulting sequence to the size of the smaller sequence, so you end up with three elements. Zip会自动将生成的序列截断为较小序列的大小,因此您最终得到三个元素。

Several solutions are available, I prefer the following one, combining LINQs Enumerable.Zip with LINQS Enumerable.Skip有几种解决方案,我更喜欢以下一种,将LINQs Enumerable.ZipLINQS Enumerable.Skip相结合

var result = list.Zip(list.Skip(1), (a, b) => (b - a) / a);
Console.WriteLine(string.Join(", ", result));

which prints哪个打印

0.25, -0.2, -0.125 0.25、-0.2、-0.125

This very compact solution allows calculation of your list like visualized here:这个非常紧凑的解决方案允许计算您的列表,如下所示:

a:    2.0        2.5        2.0       1.75
b:    2.5        2.0        1.75
res:  0.25      -0.2       -0.125

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM