在c#的list集合操作中,有时候需要将特定的对象或者元素移除出list集合序列中,此时可使用到list集合的remove方法,remove方法的方法签名为bool remove(t item),item代表具体的list集合中的对象,t是c#中泛型的表达形式。

(1)例如有个list集合list1中含有元素1至10,需要移除元素5可使用下列语句:

list<int> list1 = new list<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
list1.remove(5);

(2)如果是引用类型,需要根据具体的对象来移除,并且对象的引用地址跟list集合中的元素的引用地址一致,具体如下:

首先定义一个自定义类testmodel类,具体结构如下

   public class testmodel
    {
         public int index { set; get; }

        public string name { set; get; }
    }

然后定义个list<testmodel>的list集合,而后往集合中添加两个元素,添加完毕后再移除index=1的元素对象。

  list<testmodel> testlist = new list<consoleapplication1.testmodel>();
  testlist.add(new consoleapplication1.testmodel()
  {
     index=1,
     name="index1"
  });
  testlist.add(new consoleapplication1.testmodel()
  {
     index = 2,
     name = "index2"
  });

  var whereremove = testlist.firstordefault(t => t.index == 1);
  testlist.remove(whereremove);

上述语句执行成功后,testlist只有一个元素,只有index=2的那个元素对象。如果上述remove方法采取下列写法,将不会进行移除,因为虽然对象中所有属性值都一样,但元素的引用地址不同,不在list集合内。

var whereremove = new testmodel() { index = 1, name = "index1" };
testlist.remove(whereremove);

 

备注:原文转载自博主个人站it技术小趣屋,原文链接c#中list集合使用remove方法移除指定的对象_it技术小趣屋。