我有一个双重值列表......
1.23,1.24,1.78,174 ......
所以我想计算后继者之间的差异 - >只添加(负值应该首先是正数)...以上4个值将是0,01 +0,53( - ) - 0,04( - ) - >到使它积极...
使用for循环,很容易......任何想法如何用linq解决它?
我不确定你对负面的意思是什么,但这可能会做你想要的.这很糟糕,因为它使用副作用,但......
double prev = 0d; var differences = list.Select(current => { double diff = prev - current; prev = current; return Math.Abs(diff); }).Skip(1);
(跳过第一个值,因为它只是给出了第一个原始值和0d之间的差异.)
编辑:可能稍微好一点的是基于元素对投影的扩展方法.这会将副作用隔离在一个地方,这很好:
using System.Collections.Generic; // This must be a non-nested type, and must be static to allow the extension // method. public static class Extensions { public static IEnumerableSelectPairs (this IEnumerable source, Func selector) { using (IEnumerator iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) { yield break; } TSource prev = iterator.Current; while (iterator.MoveNext()) { TSource current = iterator.Current; yield return selector(prev, current); prev = current; } } } }
要在您的特定情况下使用此功能,您需要执行以下操作:
var differences = list.SelectPairs((x, y) => Math.Abs(x-y));