Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove elements of a List from a class containing the List?

Tags:

c#

I have a class Parent that contains a list of ParentDetail. The class works fine but now I need to provide a method that will remove any ParentDetail objects that have ParentDetail.Text as the empty string.

Is there an easy way that I can do this by adding another method to the Parent class?

public class Parent {
        public IList<ParentDetail> ParentDetails {
            get { return _ParentDetails; }
        }
        private List<ParentDetail> _ParentDetails = new List<ParentDetail>();
        public Parent() {
            this._ParentDetails = new List<ParentDetail>();
        }
    }

    public class ParentDetail {
        public ParentDetail() {
            this.Text = new HtmlText();
        }
        public HtmlText Text { get; set; }
    }

    public class HtmlText {
        public HtmlText() {
            TextWithHtml = String.Empty;
        }
        [AllowHtml]
        public string TextWithHtml { get; set; } 
    }
like image 497
UCC Avatar asked Dec 16 '22 12:12

UCC


2 Answers

public void RemoveEmptyChildren() {
     _ParentDetail.RemoveAll(
         x => x.Text == null ||
         string.IsNullOrEmpty(x.Text.TextWithHtml));
}
like image 137
Marc Gravell Avatar answered Jan 12 '23 00:01

Marc Gravell


You could also make it a little bit more generic:

public void RemoveChildren( Predicate<Child> match )
{
    _parentDetail.RemoveAll (match);
}

Then, you can use it like this:

Parent p = new Parent();
p.RemoveAll (x => x.Text == null || String.IsNullOrEmpty(x.Text.TextWithHtml));

I would also add an extra property to ParentDetail: IsEmpty

public class ParentDetail
{
   public HtmlText Text {get; set;}

   public bool IsEmpty  
   {
      return this.Text == null || String.IsNullOrEmpty(this.Text.TextWithHtml);
   }
}

Then, your code can be simplified like this:

Parent p = new Parent();
p.RemoveAll (x => x.IsEmpty);

Marc's answer is explicit (which I like), but if you want more flexibility, using a Func argument is more flexible.

like image 21
Frederik Gheysels Avatar answered Jan 12 '23 00:01

Frederik Gheysels