Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
   {
      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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading