简体   繁体   English

如何从包含List的类中删除List的元素?

[英]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. 我有一个包含ParentDetail列表的Parent类。 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. 该类工作正常,但现在我需要提供一个方法,将删除任何ParentDetail对象,其中ParentDetail.Text为空字符串。

Is there an easy way that I can do this by adding another method to the Parent class? 有没有一种简单的方法可以通过向Parent类添加另一个方法来实现这一点?

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; } 
    }
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 我还要为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. Marc的答案是明确的(我喜欢),但如果你想要更多的灵活性,使用Func参数会更灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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