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

前端 未结 26 902
迷失自我
迷失自我 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:19

    The accepted answer will not work for duplicates in the collection. If you're set on the foreach, you can just add your own indexing variable(s).

    int last = Model.Results.Count - 1;
    int index = 0;
    foreach (Item result in Model.Results)
    {
        //Do Things
    
        if (index == last)
            //Do Things with the last result
    
        index++;
    }
    

提交回复
热议问题