C#中的Remove(T)方法用于从List
以下是使用Remove(T)方法的步骤:
Step 1:创建List
首先,需要创建一个List
List<string> fruits = new List<string>();
fruits.Add("apple");//向集合中添加元素
fruits.Add("mango");
fruits.Add("banana");
Step 2:删除集合中的元素
从List
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)方法的完整攻略,包括步骤和示例代码。