EN
C# / .NET - iterate over List and remove indicated items
0 points
In this article, we would like to show you how to iterate over List and remove indicated items in C#.
Quick solution:
xxxxxxxxxx
1
List<string> myList = new List<string> { "A", "B", "C" };
2
3
for (int i = myList.Count - 1; i >= 0; i--)
4
if (myList[i] == "B")
5
myList.RemoveAt(i);
or:
xxxxxxxxxx
1
List<string> myList = new List<string> { "A", "B", "C" };
2
3
myList.RemoveAll(item => item == "B");
In this example, we use RemoveAt()
method to remove indicated items by index when the value matches the criteria.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<string> myList = new List<string> { "A", "B", "C" };
9
10
for (int i = myList.Count - 1; i >= 0; i--)
11
{
12
if (myList[i] == "B")
13
myList.RemoveAt(i);
14
}
15
16
// Print results
17
foreach (string item in myList)
18
Console.WriteLine(item);
19
}
20
}
Output:
xxxxxxxxxx
1
A
2
C
In this example, we use RemoveAll()
method to remove indicated items when they match the criteria.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<string> myList = new List<string> { "A", "B", "C" };
9
10
myList.RemoveAll(item => item == "B");
11
12
// Print results
13
foreach (string item in myList)
14
Console.WriteLine(item);
15
}
16
}
Output:
xxxxxxxxxx
1
A
2
C