對於一個List<T>對象來說移除其中的元素是常用的功能。自己總結了一下,列出自己所知的幾種方法。
class Program
{
static void Main(string[] args)
{
try
{
List<Student> studentList = new List<Student>();
for (int i = 0; i < 10; i++)
{
Student s = new Student()
{
Age = 10,
Name = "John"
};
studentList.Add(s);
}
studentList.Add(new Student("rose",9));
studentList.Add(new Student("rose", 10));
studentList.Add(new Student("rose", 11));
//不能用foreach進行刪除列表元素的操作,因為這種刪除方式破壞了索引
//foreach (var testInt in studentList)
//{
// if (testInt.Age == 10)
// studentList.Remove(testInt);
//}
Console.Read();
}
catch (Exception)
{
throw;
}
}
}
方法1:for循環倒序移除
//for循環倒序刪除
for (int i = studentList.Count - 1; i >= 0; i--)
{
if (studentList[i].Age == 10)
{
studentList.Remove(studentList[i]);
//studentList.RemoveAt(i);
}
}
方法2:for循環順序移除
//for循環順序刪除
for (int i = 0; i < studentList.Count - 1; )
{
if (studentList[i].Age==10)
{
studentList.Remove(studentList[i]);
}
i++;
}
方法3:使用RemoveAll篩選移除
studentList.RemoveAll((test) => test.Age == 10);//可以用此Linq表達式移除所有符合條件的列表元素
方法4:克隆所有非移除元素至一個新的列表中