c#List移除列表中的元素


對於一個List<T>對象來說移除其中的元素是常用的功能。自己總結了一下,列出自己所知的幾種方法。

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             try
 6             {
 7                 List<Student> studentList = new List<Student>();
 8                 for (int i = 0; i < 10; i++)
 9                 {
10                     Student s = new Student()
11                     {
12                         Age = 10,
13                         Name = "John"
14                     };
15                     studentList.Add(s);
16                 }
17                 studentList.Add(new Student("rose",9));
18                 studentList.Add(new Student("rose", 10));
19                 studentList.Add(new Student("rose", 11));
20 
21                22                 31                 40                 //不能用foreach進行刪除列表元素的操作,因為這種刪除方式破壞了索引
41                 //foreach (var testInt in studentList)
42                 //{
43                 //    if (testInt.Age == 10)
44                 //        studentList.Remove(testInt);
45                 //}
46                 Console.Read();
47             }
48             catch (Exception)
49             {
50 
51                 throw;
52             }
53             
54             
55         }
56     }

 

方法1:for循環倒序移除

//for循環倒序刪除
23                 for (int i = studentList.Count - 1; i >= 0; i--)
24                 {
25                     if (studentList[i].Age == 10)
26                     {
27                         studentList.Remove(studentList[i]);
28                         //studentList.RemoveAt(i);
29                     }
30                 }

  

方法2:for循環順序移除//for循環順序刪除

 

for (int i = 0; i < studentList.Count - 1; )
{
    if (studentList[i].Age==10)
    {
        studentList.Remove(studentList[i]);
    }
    else
    { 
        i++;
    }
}

  

方法3:使用RemoveAll篩選移除

 studentList.RemoveAll((test) => test.Age == 10);//可以用此Linq表達式移除所有符合條件的列表元素

  

方法4:克隆所有非移除元素至一個新的列表中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM