Mar152013

Tip: Loop Through a Collection Backwards [C#]

There are times where it's beneficial to iterate through a collection backwards; e.g. processing and removing records from a set. While this technique is nothing groundbreaking, I thought I'd share this cool shorthand for the backwards iteration:

var records = getMyRecords();

for(var i = records.Length; i-- > 0;) { var record = records\[i\];

// Additional processing processMyRecord(record);

records.RemoveAt(i); }

This is the part that's most interesting:

for(var i = records.Length; i-- > 0;)

At first glance it looks like you might be subject to an off-by-one error, but due to how the for is actually evaluated, this works perfectly.

Found via Stack Overflow.