在C#的List集合操作中,有时候需要将特定的对象或者元素移除出List集合序列中,此时可使用到List集合的Remove方法,Remove方法的方法签名为bool Remove(T item),item代表具体的List集合中的对象,T是C#中泛型的表达形式。
(1)例如有个List集合list1中含有元素1至10,需要移除元素5可使用下列语句:
List list1 = new List() { 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的List集合,而后往集合中添加两个元素,添加完毕后再移除Index=1的元素对象。
List 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技术小趣屋。