IEnumerable foreach, do something different for the last element

后端 未结 5 2325
庸人自扰
庸人自扰 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:51

    I wouldn't really recommend it, but I guess you could do something like this...

    object m_item = notPartOfListFlag = new object();
    foreach(var item in enumerator){
       if(m_item != notPartOfListFlag)
       {
          //do stuff to m_item;
       }
       m_item = item;
    }
    //do stuff to last item aka m_item;
    

    But I would try to use some kind of collection that exposes the position of the items in the list, then use

    if(collection.IndexOf(item) == collection.Count-1) do stuff
    

提交回复
热议问题