how do access previous item in list using linQ?

后端 未结 5 664
南笙
南笙 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:27

    Ok so getting the Next item in the list you can use:

    A.SkipWhile(x => x != value).Skip(1).FirstOrDefault();
    

    So to get the previous item use:

    var B = A.ToList();
    B.Reverse();
    B.SkipWhile(x => x != value).Skip(1).FirstOrDefault();
    
    0 讨论(0)
  • 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<int>();
    
    for(int i = 1; i < A.Count; i++)
       sumsOfConsecutives.Add(A[i] + A[i - 1]);
    
    0 讨论(0)
  • 2020-12-14 03:34

    How about something like

    var l = A.Skip(1).Select((x, index) => x + A[index]).ToList();
    
    0 讨论(0)
  • 2020-12-14 03:35

    In case you only need the end value, you can Aggregate it, ie. you need previous value, but dont need each individual value to a new list.

    int last = 0;
    var r = m.Aggregate(last, (acc, it) => (last += it), (acc) => (last));
    
    0 讨论(0)
  • 2020-12-14 03:40

    Some of the other answers assume that the elements of A are always going to be 1, 2, 3, 4, 5, 6. If those values ever change then the solution would break, such as the values changing to 2, 3, 6, 7, 10.

    Here's my solution that will work with any values of A.

    List<int> m = A.Skip(1).Select((element, index) => element + A.ElementAt(index)).ToList();
    

    It is worth noting that sticking with a loop would probably be better than hacking together a Linq solution for this.

    0 讨论(0)
提交回复
热议问题