0

I have a list that some of its members are ""so I want to remove them and I used foreach and mylist.remove(elements) but after one iteration it doesn't work and I think the problem is in changing the size of the list

foreach (string element in list)
{
    if (element=="")
    {
        list.Remove(element);
    }
}
Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
Ali Madani
  • 11
  • 2

3 Answers3

2

You can use System.Linq, as so:

list = list.Where(x => x != "").ToList();

Or, if you also want to remove those elements which equal NULL, use the below:

list = list.Where(x => !string.IsNullOrEmpty(x)).ToList();

If you want to do it without Linq, you can.

for (int i = 0; i < list.Count; i++)
{
    if (string.IsNullOrEmpty(element))
    {
        list.RemoveAt(i);
        i--;
    }
}
Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
1

Short Answer: You do not.

Long Answer: foreach does not work with collections, it only works with Enumerators. Luckily every collection and their dog can be converted into a Enumerator. It just did that implicitly without you even noticing it.

However one standing rule of Enumerators that should always be followed is: if the underlying collection changes, the Enumerator must become invalid.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerator?view=netframework-4.8

"If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined. "

And just to be certain to not cause any issues, most Enumerators just throw an Exception.

Edit: Linq Solutions

The Linq Solutions posted by others get around that. While it propably uses a foreach (IIRC the linq expression actually is a enumerator), it does not change the list. It just creates a new list with the elements you filtered for. None of the headache, but linq can cause memory issues in extreme or fringe cases (large lists, webapplications) - just in case you need to mind your memory profile.

Christopher
  • 9,634
  • 2
  • 17
  • 31
1

Use List<T>.RemoveAll() to do an in-place remove that does not involve creating a new list:

list.RemoveAll(element => element == "");

Or if elements can be null and you also want to remove them:

list.RemoveAll(element => element == null || element == "");

or (shorter and more self-descriptive):

list.RemoveAll(string.IsNullOrEmpty);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276