简体   繁体   中英

Remove Items from recursive list by property

I have a data-structure like this

public class DomainObject
{
    public List<DomainObject> Children { get; private set; }
    public List<Car> Cars { get; private set; }
}

public class Car 
{
    public bool Sold { get; }
}

So my structure is quite nested and I want to remove all Car which aren't flagged as Sold .

Here an example of what I actually want

List
  DomainObject
    Children
      Car A (Sold)
      Car B (!Sold)
      Car C (Sold)
    Children
      Car D (!Sold)
      Car E (!Sold)
      Car F (Sold)

becomes

List
  DomainObject
    Children
      Car A
      Car C
    Children
      Car F

A recursive function should do it.

public void RemoveNonSoldCars(DomainObject parent)
{
    parent.Cars.RemoveAll(x => !x.Sold);
    foreach (var item in parent.Children)
        RemoveNonSoldCars(item);
}

Create a method that takes the DomainObject then removes all non-sold cars from their Cars variable. That could be done with a reverse for loop or using RemoveAll with linq . End the method by calling itself for all children objects in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM