Question

Remove In Nested Loops (Remove Inside Foreach)

These are my entities:

public class Permissions
{
    public string PermissionName { get; set; }
    public List<Controllers> controllers { get; set; }
}
public class Controllers
{
    public string ControllerName { get; set; }
    public List<Actions> actions { get; set; }
}
public class Actions
{
    public string ActionName { get; set; }
    public bool Active { get; set; }
}

I want Remove Controllers that Have DeActive actions...

    var a1 = new Actions() { ActionName = "Action1", Active = false };
    var a2 = new Actions() { ActionName = "Action2", Active = true };
    var a3 = new Actions() { ActionName = "Action3", Active = true };
    var a4 = new Actions() { ActionName = "Action4", Active = true };

    var c1 = new Controllers() { ControllerName = "Controller1", actions = new List<Actions>() { a1, a2 } };
    var c2 = new Controllers() { ControllerName = "Controller2", actions = new List<Actions>() { a3, a4 } };

    var ListOfPermision = new List<Permissions>()
    {
         new Permissions() { PermissionName = "P1", controllers = new List<Controllers>() { c1, c2 } }
    };
    //First Way:-------------------------------
    ListOfPermision.ForEach(p =>
      p.controllers.ForEach(c =>
          c.actions.ForEach(a =>
          {
              if (!a.Active)
              {
                  //Remove Controller
              }
          }
     )));
    //OR Second Way:----------------------------
    foreach (var p in ListOfPermision)
    {
        foreach (var c in p.controllers)
        {
            foreach (var a in c.actions)
            {
                if (!a.Active)
                {
                    //Remove Controller
                }
            }
        }
    }
    //----------------------------------

The following statement should delete some Controllers Because that controllers have At least one action with Active=False... I Dont know What Is The Best way i should to do... What if I want to delete the controller whose action count is 0? Thank You Guys For Your Time

 3  73  3
1 Jan 1970

Solution

 5

instead of modifying the collection you're iterating, you could just create a copy and iterate that, while removing items form the original.

Or even simpler:

foreach (var p in ListOfPermision)
{
    p.Controllers = p.Controllers.Where(x => x.Actions.Any(y => !y.Active)).ToList();
}

this will query all the controllers where at least one Action is not Active and store the result in the p.Controllers-property.

You can also use RemoveAll on a List<T>, which expects a Predicate<T>:

p.Controllers.RemoveAll(x => x.Actions.Any(y => !y.Active));

or when you want to remove all controllers that have no Action:

p.Controllers.RemoveAll(x => !x.Actions.Any());
2024-07-02
MakePeaceGreatAgain