如何从List <t> </t>中删除特定对象

时间:2014-04-06 23:18:06

标签: c# list oop object

所以我去了一个存储Feeds对象的列表,这些对象是用链接和类别构建的。现在我想删除一个具有特定链接和类别的给定Feeds对象。

我的清单声明:

public void addFeed(String link, String cat) {
    linkAcategory.Add(new feed(link, cat));
}

添加功能:

public void addFeed(String link, String cat) {
    linkAcategory.Add(new feed(link, cat));
}

删除功能无效但显示我正在尝试做的事情:

public void removeFeed(String link, String cat) {
    linkAcategory.Remove(new feed(link,cat));
}

我希望我能得到任何有价值的帮助。 提前谢谢。

3 个答案:

答案 0 :(得分:7)

假设T对象具有link和cat属性:

linkAcategory.RemoveAll(x=>x.link==link && x.cat==cat);

答案 1 :(得分:0)

List对象提供了三种删除元素的方法。

  1. 按lambda条件删除所有元素

  2. 按索引删除特定元素

  3. 自行删除特定元素

  4. 例如

    List<int> myList = new List<int>()
                {
                    2,
                    1,
                    3,
                    1
                };
    
     myList.Remove(1);// Delete 1-element from the index 1
     myList.RemoveAt(0);// Delete 2-element from the index 0
     myList.RemoveAll(x => x == 1);// Delete all elements that equal to 1
    

答案 2 :(得分:0)

编写removeFeed方法时,Feed类应覆盖Equals方法。有点像:

    public class Feed
    {
        private string link;
        private string cat;

        …

        public override bool Equals(object obj)
        {
            if (obj == null) return false;

            var other = obj as Feed;
            if (other == null) return false;

            return other.link == this.link && other.cat == this.cat;
        }
    }

这是因为其元素的Remove method of List uses the Equals方法。

如果要将某些属性保留为私有属性,可以选择此方法。这样,调用类必须知道的唯一方法是Equals方法。它不必知道确定相等性的属性。