【转载】C#中List集合使用Remove方法移除指定的对象

在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);

 

C#编写的扫雷游戏源码(完整解决方案源码,可以直接编译运行):https://pan.baidu.com/s/1T4zVndyypzY9i9HsLiVtGg。提取码请关注博主公众号后,发送消息:扫雷源码。

 

posted @ 2019-06-15 19:04  江湖逍遥  阅读(30408)  评论(1编辑  收藏  举报