Alex Rivera | Logout

How can I access the next value in a collection inside a foreach loop in C#?

Asked 2010-03-08T19:44:54.443
45

I'm working in C# and with a sorted List<T> of structs. I'm trying to iterate through the List and for each iteration I'd like to access the next member of the list. Is there a way to do this?

Pseudocode example:

foreach (Member member in List)
{
    Compare(member, member.next);
}
Edit
Report

2 Answers

69

You can't. Use a for instead

for(int i=0; i<list.Count-1; i++)
   Compare(list[i], list[i+1]);
answered 2010-03-08T19:47:22.060
4

LINQ might be your friend here. This approach will work with anything that's IEnumerable<T>, not just IList<T> collections, which is very useful if your collection never ends or is otherwise calculated on-the-fly:

class Program {
    static void Main(string[] args) {
        var list = new List<Int32> { 1, 2, 3, 4, 5 };
        foreach (var comparison in list.Zip(list.Skip(1), Compare)) {
            Console.WriteLine(comparison);
        }
        Console.ReadKey();
    }

    static Int32 Compare(Int32 first, Int32 second) {
        return first - second;
    }
}
answered 2010-03-08T20:10:38.287

Your Answer