LINQ:双值的列表 - 后继值之间的差异 [英] Linq: List of double values - differences between successor values

查看:149
本文介绍了LINQ:双值的列表 - 后继值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有双重值的列表...

i have a list of double values...

1.23,1.24,1.78,1.74 ...

1.23, 1.24, 1.78, 1,74...

所以我要计算的继任者之间的区别 - >只增加(负值应先正)...上面4个值是0.01 +0,53( - ) - $ 0.04 b $ b( - ) - >,使其积极...

so i want to calculate the differences between the successor -> only adding (negative values should be firstly positive)... above 4 values would be 0,01 +0,53 (-)-0,04 (-) -> to make it positive...

与for循环,很容易...任何想法如何使用LINQ解决?

with an for-loop, it is easy... any idea how to solve it with linq?

推荐答案

我不知道你的意思的负面位是什么,但是这可能会做你想要什么。这是可怕的,因为它使用的副作用,但是......

I'm not sure what you mean about the negative bits, but this might do what you want. It's horrible because it uses side effects, but...

double prev = 0d;
var differences = list.Select(current =>
    {
       double diff = prev - current;
       prev = current;
       return Math.Abs(diff);
    }).Skip(1);



(第一个值被跳过,因为它只是给第一原始值和0D之间的差异。)

(The first value is skipped because it just gives the difference between the first original value and 0d.)

编辑:什么可能是略微更好将是项目的基础上对元素的扩展方法。这样可以隔离在一个地方,这是很好的副作用:

What might be slightly nicer would be an extension method to project based on pairs of elements. This isolates the side-effects in one place, which is fine:

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 IEnumerable<TResult> SelectPairs<TSource, TResult>
        (this IEnumerable<TSource> source,
         Func<TSource, TSource, TResult> selector)
    {
        using (IEnumerator<TSource> 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;
           }
        }
    }
}

要在特定情况下使用它,你会怎么做:

To use this in your particular case, you'd do:

var differences = list.SelectPairs((x, y) => Math.Abs(x-y));

这篇关于LINQ:双值的列表 - 后继值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆