How to remove items from a list from a class containing a list?

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

Is there an easy way 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; } } 
+4
source share
2 answers
 public void RemoveEmptyChildren() { _ParentDetail.RemoveAll( x => x.Text == null || string.IsNullOrEmpty(x.Text.TextWithHtml)); } 
+11
source

You can also make it a little more general:

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

Then you can use it as follows:

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

I would add an additional 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 as follows:

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

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

+1
source

All Articles