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

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

    Using Last() on certain types will loop thru the entire collection!
    Meaning that if you make a foreach and call Last(), you looped twice! which I'm sure you'd like to avoid in big collections.

    Then the solution is to use a do while loop:

    using var enumerator = collection.GetEnumerator();
    
    var last = !enumerator.MoveNext();
    T current;
    
    while (!last)
    {
      current = enumerator.Current;        
    
      //process item
    
      last = !enumerator.MoveNext();        
      if(last)
      {
        //additional processing for last item
      }
    }
    

    So unless the collection type is of type IList the Last() function will iterate thru all collection elements.

    Test

    If your collection provides random access (e.g. implements IList), you can also check your item as follows.

    if(collection is IList list)
      return collection[^1]; //replace with collection.Count -1 in pre-C#8 apps
    

提交回复
热议问题