我有一个列表。
1 2 3 4 5 6 7
我希望返回连续元素之间的差异(增量)列表。
1 1 1 1 1 1
我该怎么做?
我确信一定有一种简单的“集合”方式可以做到这一点 - 但我找不到它。
最佳答案
您可以使用 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();
诀窍在于 Skip(1)
不仅会跳过第一个数字(这是需要的),还会更改 Select
中的索引。第一个数字的 index
将为 0,但它会引用列表中的第二个数字(由于 Skip(1)
)。因此 num - list[index]
用前一个数减去当前数。
关于c# - 如何获取列表集合的增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26587845/