Get previous element in foreach

5

Is it possible to take an element from the previous position to the current position using the foreach loop?

For example, whenever I need to pick up an element earlier than the current loop position, I use the for loop as follows:

List<int> ListaDados = new List<int>();

ListaDados.Add(1); ListaDados.Add(2); ListaDados.Add(3); ListaDados.Add(5);

for(int i=1; i < ListaDados.Count; i++) {      
    var elementoAtual = ListaDados[i];
    var elementoAnterior = ListaDados[i-1];
}
    
asked by anonymous 24.01.2018 / 14:47

2 answers

5

Yes, it is possible:

using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var lista = new List<int>() { 1, 2, 3, 4 };
        var anterior = 0;
        foreach (var item in lista) {
            WriteLine($"Soma o atual e anterior { anterior + item }");
            anterior = item;
        }
    }
}

The exact way you implement this depends on your need. In some cases it may be interesting to put a comparison to avoid the first run, since C # does not handle this execution differently and does not intend to have it in the language.

In structures you create or can extend you can create a specific enumerator that gives you access to the previous element, but that's another matter.

I do not like the other answer, it is absurdly slower, with possibly quadratic complexity (in% with% certainly, and double in complexity). And I think it's wrong because if you have duplicate items it will give you an error.

    
24.01.2018 / 15:07
0

As Gabriel commented, "by definition the foreach will invoke the IEnumerable.GetEnumerator to do its incrementation, it does not use the index as < strong> for ".

But there is an alternative (which I believe is not very viable) if you want to even use foreach :

List<int> ListaDados = new List<int>();

ListaDados.Add(1); ListaDados.Add(2); ListaDados.Add(3); ListaDados.Add(5);

freach (int elementoAtual in ListaDados){

    if (ListaDados.IndexOf(elementoAtual) == 0)
        // não existe elemento anterior
    else
    {
        var elementoAnterior = ListaDados.ElementAt(ListaDados.IndexOf(elementoAtual));

        //todo: seu código
    }
}
    
24.01.2018 / 15:07