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

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

    The iterator implementation does not provide that. Your collection might be an IList that is accessible via an index in O(1). In that case you can use a normal for-loop:

    for(int i = 0; i < Model.Results.Count; i++)
    {
      if(i == Model.Results.Count - 1) doMagic();
    }
    

    If you know the count, but cannot access via indices (thus, result is an ICollection), you can count yourself by incrementing an i in the foreach's body and comparing it to the length.

    All this isn't perfectly elegant. Chris's solution may be the nicest I've seen so far.

提交回复
热议问题