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;
}
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
The exact way to implement this depends on your need. In some cases it may be interesting to put a comparison to avoid the first execution, since C# does not treat this execution differently and does not intend to have this in the language.
In structures you create or can extend it is possible to create a specific enumerator that gives you access to the previous element, but that is another matter.
I don’t like the other answer, it is absurdly slower, with possibly quadratic complexity (in List
certainly, and it’s double). And I think it’s even wrong because if you have duplicate items will give error.
No, by definition the foreach will invoke Ienumerable.Getenumerator to perform its increment, it does not use index as FOR.
– Gabriel Coletta
Just as a detail, this code would give execution error in the first iteration of for, since there is no element in the position
-1
ofListaDados
– rLinhares
Use a
for
common is by far the best solution.– Jéf Bueno