Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - how do access previous item in list using linQ?

I have:

List<int> A  = new List<int>(){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);
}

how can i do this same operation using LinQ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

There's nothing really wrong with:

var sumsOfConsecutives = new List<int>();

for(int i = 1; i < A.Count; i++)
   sumsOfConsecutives.Add(A[i] + A[i - 1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...