如何获取列表集合的增量

Man*_*oon 2 c# collections

我有一份清单.

1 2 3 4 5 6 7

我希望返回连续元素之间的差异列表(增量).

1 1 1 1 1 1

我怎样才能做到这一点?

我确信必须有一个简单的"集合"方式 - 但我找不到它.

Tim*_*ter 7

您可以使用Enumerable.Skip和重载Enumerable.Select项目的索引:

List<int> deltaList = list.Skip(1)             // skip first, irrelevant
    .Select((num, index) => num - list[index]) // index 0 is second number in list
    .ToList();
Run Code Online (Sandbox Code Playgroud)

诀窍是Skip(1)不仅跳过第一个数字(这是期望的)而且还改变了索引Select.第一个数字index将为0,但它将引用列表中的第二个数字(由于Skip(1)).因此num - list[index],用前一个数字减去当前的电流.


mih*_*hai 5

var result = list.Zip(list.Skip(1), (x, y) => y - x);
Run Code Online (Sandbox Code Playgroud)