IEnumerable foreach, do something different for the last element

后端 未结 5 2295
庸人自扰
庸人自扰 2021-02-20 06:23

I have an IEnumerable. I want to do one thing for each item of the collection, except the last item, to which I want to do something else. How can I code this neatly? I

5条回答
  •  盖世英雄少女心
    2021-02-20 06:31

    not 100% sure I like this but you could always delay the use of item until you've moved one step in to the IEnumerable array, that way when you get to the end you've not used the last entry.

    it avoids having to force a count on the enumerator.

    object item = null;
    foreach (var a in items)
    {
      // if item is set then we can use it.
      if (item != null)
      {
          // not final item
          f(item);
      }
      item = a;
    }
    
    // final item.
    g(item);
    

提交回复
热议问题