foreach (Item i in Items)
{
do something with i;
do another thing with i (but not if last item in collection);
}
Better to use a for loop:
int itemCount = Items.Count;
for (int i = 0; i < itemCount; i++)
{
var item = Items[i];
// do something with item
if (i != itemCount - 1)
{
// do another thing with item
}
}
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're using .NET 3.5 and C# 3 so you can use extension methods and implicit typing:
foreach (var entry in list.AsSmartEnumerable())
{
Console.WriteLine ("{0,-7} {1} ({2}) {3}",
entry.IsLast ? "Last ->" : "",
entry.Value,
entry.Index,
entry.IsFirst ? "<- First" : "");
}
The nice thing about this over 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 maintains a single-entry buffer internally, mind you.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With