Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a foreach loop during last iteration?

Tags:

c#

list

foreach (Item i in Items)

 {
      do something with i;
      do another thing with i (but not if last item in collection);
 }
like image 714
zsharp Avatar asked Nov 26 '22 22:11

zsharp


2 Answers

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
    } 
}
like image 164
Ben M Avatar answered Nov 29 '22 12:11

Ben M


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.)

like image 26
Jon Skeet Avatar answered Nov 29 '22 13:11

Jon Skeet