c# – Why List<T> .Remove (T) only removes the first matching element?

Question:

I have the following problem.

I have a List<string> with information that can vary depending on the actions taken and I need to remove all the elements that match the string .

I have tried the following code in the List<T> :

List<string> Strings = new List<string>() {
    "658", "123", "321", "123"
};
foreach (string s in Strings) Console.WriteLine(s); // Imprime: 658, 123, 321, 123
Strings.Remove("123");
foreach (string s in Strings) Console.WriteLine(s); // Imprime: 658, 321, 123

And I need the last foreach loop to return 658, 321 .

I know I can loop through the List , but I need to understand why not all matching items are removed.

Greetings.

Answer:

There are several alternatives for what you are looking for, you could use

List<string> Strings = new List<string>() {
    "658", "123", "321", "123"
};

foreach (string s in Strings) Console.WriteLine(s);
Strings.RemoveAll(x=> x=="123");
foreach (string s in Strings) Console.WriteLine(s);

or help you with linq

List<string> Strings = new List<string>() {
    "658", "123", "321", "123"
};

foreach (string s in Strings) Console.WriteLine(s);
Strings = Strings.Where(x=> x != "123").ToList();
foreach (string s in Strings) Console.WriteLine(s);

with linq you basically filter by removing the value you don't want

Scroll to Top