how do access previous item in list using linQ?

后端 未结 5 681
南笙
南笙 2020-12-14 03:24

I have:

List A  = new List(){1,2,3,4,5,6};

List m=new List();
for(int i=1;i

        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 03:33

    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();
    
    for(int i = 1; i < A.Count; i++)
       sumsOfConsecutives.Add(A[i] + A[i - 1]);
    

提交回复
热议问题