I have a helper class for this in MiscUtil . Sample code (from the first link):
foreach (SmartEnumerable<string>.Entry entry in new SmartEnumerable<string>(list)) { Console.WriteLine ("{0,-7} {1} ({2}) {3}", entry.IsLast ? "Last ->" : "", entry.Value, entry.Index, entry.IsFirst ? "<- First" : ""); }
This is simpler if you use .NET 3.5 and C # 3 to use extension methods and implicit spelling:
foreach (var entry in list.AsSmartEnumerable()) { Console.WriteLine ("{0,-7} {1} ({2}) {3}", entry.IsLast ? "Last ->" : "", entry.Value, entry.Index, entry.IsFirst ? "<- First" : ""); }
The good thing about this using a for loop is that it works with IEnumerable<T> instead of IList<T> , so you can use it with LINQ, etc. without buffering everything. (It supports an internal single-input buffer, mind you.)
source share