Collection < T > .Remove(T)用于从Collection
句法:
public bool Remove (T item);
这里, item是要从Collection < T >中删除的对象。对于引用类型,该值可以为null。
返回值:如果项已成功删除,则为True ,否则为False 。如果在原始Collection < T >中找不到该项目,则此方法还返回False。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to remove the first
// occurrence of a specific object
// from the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of strings
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add("A");
myColl.Add("B");
myColl.Add("C");
myColl.Add("D");
myColl.Add("E");
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
// Removing the first occurrence of
// a specific object from the Collection
myColl.Remove("C");
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
}
}
输出:
Count : 5
A
B
C
D
E
Count : 4
A
B
D
E
范例2:
// C# code to remove the first
// occurrence of a specific object
// from the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of ints
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(4);
myColl.Add(5);
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
// Removing the first occurrence of
// a specific object from the Collection
myColl.Remove(4);
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
}
}
输出:
Count : 5
2
3
4
4
5
Count : 4
2
3
4
5
注意:此方法执行线性搜索。因此,此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.remove?view=netframework-4.7.2