如何使用LINQ在访问列表上一个项目? [英] how do access previous item in list using linQ?
本文介绍了如何使用LINQ在访问列表上一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有列表A中包含{} 1,2,3,4,5,6
I have List A contains{1,2,3,4,5,6}
List<int> m=new List<int>();
for(int i=1;i<A.count;i++)
{
int j=A[i]+A[i-1];
m.add(j);
}
我如何能做到使用LINQ此相同的操作?
how can i do this same operation using LinQ?
推荐答案
好了,一个简单的翻译是:
Well, a straightforward translation would be:
var m = Enumerable.Range(1, A.Count - 1)
.Select(i => A[i] + A[i - 1])
.ToList();
还要考虑:
But also consider:
var m = A.Skip(1)
.Zip(A, (curr, prev) => curr + prev)
.ToList();
或使用乔恩斯基特的扩展名的这里:
Or using Jon Skeet's extension here:
var m = A.SelectWithPrevious((prev, curr) => prev + curr)
.ToList();
不过贾森·埃文斯在评论中指出,这并不能帮助所有的东西与可读性或简洁,考虑到现有的代码是完全可以理解的(短),并要兑现的所有的结果到一个列表中的反正。
But as Jason Evans points out in a comment, this doesn't help all that much with readability or brevity, considering your existing code is perfectly understandable (and short) and you want to materialize all of the results into a list anyway.
有没有什么错:
var sumsOfConsecutives = new List<int>();
for(int i = 1; i < A.Count; i++)
sumsOfConsecutives.Add(A[i] + A[i - 1]);
这篇关于如何使用LINQ在访问列表上一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文