How can I remove elements of a List from a class containing the List?
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;
}
[AllowHtm开发者_JS百科l]
public string TextWithHtml { get; set; }
}
public void RemoveEmptyChildren() {
_ParentDetail.RemoveAll(
x => x.Text == null ||
string.IsNullOrEmpty(x.Text.TextWithHtml));
}
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.
精彩评论