C# Remove(T):从 ICollection中移除特定对象的第一个匹配项

  • Post category:C#

C#中的Remove(T)方法用于从List集合中删除某一项,其中T为集合中元素的数据类型。该方法有一个参数,即要删除的元素值,如果该元素存在于集合中,则会被删除,否则操作无效。

以下是使用Remove(T)方法的步骤:

Step 1:创建List集合

首先,需要创建一个List集合对象,其泛型类型为T,例如:

List<string> fruits = new List<string>();
fruits.Add("apple");//向集合中添加元素 
fruits.Add("mango");
fruits.Add("banana");

Step 2:删除集合中的元素

从List集合中删除元素只需调用Remove(T)方法并传递要删除的元素值作为参数即可,例如:

fruits.Remove("mango");

上述代码将会从fruits集合中删除值为“mango”的元素。

以下是删除集合中指定元素示例代码:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        //创建List<T>集合
        List<string> fruits = new List<string>();
        fruits.Add("apple");
        fruits.Add("orange");
        fruits.Add("mango");
        fruits.Add("banana");

        Console.WriteLine("原来的集合:");
        DisplayCollection(fruits);

        //从集合中移除指定元素
        fruits.Remove("mango");

        Console.WriteLine("删除后的集合:");
        DisplayCollection(fruits);

        Console.ReadKey();
    }

    static void DisplayCollection(List<string> collection)
    {
        foreach (var item in collection)
        {
            Console.Write("{0} ", item);
        }
        Console.WriteLine();
    }
}

输出结果:

原来的集合:
apple orange mango banana 
删除后的集合:
apple orange banana 

以下是在多个集合中删除指定元素的示例代码:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        //创建多个List<T>集合
        List<string> fruits1 = new List<string>() { "apple", "orange", "mango", "banana" };
        List<string> fruits2 = new List<string>() { "apple", "orange", "pear", "grape" };
        List<string> fruits3 = new List<string>() { "coconut", "orange", "lemon", "mango" };

        Console.WriteLine("原来的集合:");
        DisplayCollection(fruits1);
        DisplayCollection(fruits2);
        DisplayCollection(fruits3);

        //删除指定元素
        string elementToRemove = "mango";

        fruits1.Remove(elementToRemove);
        fruits2.Remove(elementToRemove);
        fruits3.Remove(elementToRemove);

        Console.WriteLine("删除后的集合:");
        DisplayCollection(fruits1);
        DisplayCollection(fruits2);
        DisplayCollection(fruits3);

        Console.ReadKey();
    }

    static void DisplayCollection(List<string> collection)
    {
        foreach (var item in collection)
        {
            Console.Write("{0} ", item);
        }
        Console.WriteLine();
    }
}

输出结果:

原来的集合:
apple orange mango banana 
apple orange pear grape 
coconut orange lemon mango 
删除后的集合:
apple orange banana 
apple orange pear grape 
coconut orange lemon 

以上就是使用C#中的Remove(T)方法的完整攻略,包括步骤和示例代码。