Foreach loop, determine which is the last iteration of the loop

前端 未结 26 906
迷失自我
迷失自我 2020-11-28 02:56

I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

 foreach (Item result in Mod         


        
26条回答
  •  一向
    一向 (楼主)
    2020-11-28 03:06

    The best approach would probably be just to execute that step after the loop: e.g.

    foreach(Item result in Model.Results)
    {
       //loop logic
    }
    
    //Post execution logic
    

    Or if you need to do something to the last result

    foreach(Item result in Model.Results)
    {
       //loop logic
    }
    
    Item lastItem = Model.Results[Model.Results.Count - 1];
    
    //Execute logic on lastItem here
    

提交回复
热议问题