Search code examples
c#loops

Finally construct for loop?


I have a number of loops that needs to have a update function run after they finish, except of course if the collection is empty.

This leads to loops like the example below. I know the if statement could just be on the Update() call only, but I was wondering if there is a construct like finally that works with loops in C#?

if (myList.Count > 0)
{
    foreach (Item it in myList)
    {
        it.Delete();
    }
    myList.Update();
}

I imagine something looking like this:

foreach (Item it in myList)
{
    it.Delete();
}
finally 
{ 
    myList.Update(); 
}


Solution

  • You could write an extension method:

    public static void IterateWithFinalAction<T>(this ICollection<T> collection, Action<T> foreachAction, Action finalAction)
    {
       if(collection.Count == 0)
       {
          return;
       }
    
       foreach(var item in collection)
       {
          foreachAction.Invoke(item);
       }
       finalAction.Invoke();
    }
    

    Usage is

    myList.IterateWithFinalAction(x => x.Delete(), () => myList.Update());
    

    Online-demo: https://dotnetfiddle.net/Q0wcyp