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 loop to foreach
return 658, 321
.
I know I can loop through the List
, but I need to understand why not all matching elements are removed.
Greetings.
There are several alternatives for what you are looking for, you could use
or help you with linq
with linq you basically filter by removing the value you don't want
The
Remove
only removes the first element, to remove all matches you have several options:Use the
RemoveAll
( documentation ), specifically:It is important to note that he
RemoveAll
updates the current list.Another good option is to use Linq to do it (with
Select
):Also with Linq but with
where
(I prefer the del optionSelect
):I'm not a C# expert but maybe you should use the RemoveAll method instead of Remove