List.Remove(T)方法用于从列表中删除第一次出现的特定对象。
列表的属性:
- 它与数组不同。列表可以动态调整大小,但数组则不能。
- List类可以接受null作为引用类型的有效值,并且还允许重复元素。
- 如果计数等于容量,则列表的容量将通过重新分配内部数组而自动增加。在添加新元素之前,现有元素将被复制到新数组。
句法:
public bool Remove (T item);
范围:
item: Specified object which is to be remove from the List.
返回类型:如果项已成功删除,则此方法返回True。否则返回False 。
注意:如果在列表中未找到项目,则此方法返回False。
以下程序说明了如何从列表中删除指定的元素:
范例1:
// C# program to remove the specified
// element from the List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of integers
List firstlist = new List();
// adding elements in firstlist
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
// Displaying elements of firstlist
// by using foreach loop
Console.WriteLine("Before Removing");
foreach(int element in firstlist)
{
Console.WriteLine(element);
}
// Removing 2 from the firstlist & Displaying
// the remaining firstlist elements
Console.WriteLine("After Removing");
firstlist.Remove(2);
foreach(int element in firstlist)
{
Console.WriteLine(element);
}
}
}
输出:
Before Removing
1
2
3
4
After Removing
1
3
4
范例2:
// C# program to remove the specified
// element from the List
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of integers
List firstlist = new List();
// adding elements in firstlist
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
// Adding some duplicate
// elements in firstlist
firstlist.Add(2);
firstlist.Add(4);
// Displaying elements of firstlist
// by using foreach loop
Console.WriteLine("Before Removing");
foreach(int element in firstlist)
{
Console.WriteLine(element);
}
// Removing first occurrence of 2
// from the firstlist & Displaying
// the remaining firstlist elements
Console.WriteLine("After Removing");
firstlist.Remove(2);
foreach(int element in firstlist)
{
Console.WriteLine(element);
}
}
}
输出:
Before Removing
1
2
3
4
2
4
After Removing
1
3
4
2
4
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.7.2