如何在上次迭代期间转义foreach循环?

zsh*_*arp 4 c# list

foreach (Item i in Items)

 {
      do something with i;
      do another thing with i (but not if last item in collection);
 }
Run Code Online (Sandbox Code Playgroud)

Ben*_*n M 24

最好使用for循环:

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
    } 
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 10

我在MiscUtil中有一个帮助类.示例代码(来自第一个链接):

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" : "");
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是.NET 3.5和C#3,那么这可以更简单,因此您可以使用扩展方法和隐式类型:

foreach (var entry in list.AsSmartEnumerable())
{
    Console.WriteLine ("{0,-7} {1} ({2}) {3}",
                       entry.IsLast  ? "Last ->" : "",
                       entry.Value,
                       entry.Index,
                       entry.IsFirst ? "<- First" : "");
}
Run Code Online (Sandbox Code Playgroud)

关于使用for循环这个问题的好处是它可以使用它IEnumerable<T>而不是IList<T>你可以使用它与LINQ等而不缓冲一切.(它在内部维护一个单项缓冲区,请注意.)