0

Is there any way I can search List<T> and remove empty items?

 ObservableCollection ListOfTnAGroupAccs <Model>

        foreach (var item in ListOfTnAGroupAccs)
        {
            if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
            {
                ListOfTnAGroupAccs.Remove(item);
                continue;
            }
        }

it gives me "Collection was modified; enumeration operation may not execute"

I can use this

        var nList = ListOfTnAGroupAccs.Where(l => l.Prefix != "" && l.ReportingGrp != "" && l.AccMngInitials != "" && l.Description != "").ToList();

But my curiosity is there any better way to do it?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
AliAzra
  • 889
  • 1
  • 9
  • 28
  • you'd probably need to log the items you want to remove inside another variable and then run a bulk removal of all of them after your loop finishes. But the linq version is reasonable, if it works. – ADyson Feb 27 '19 at 14:45

3 Answers3

2

You cannot remove items while iterationg them, and thus the exception. One way to do it is to do a regular backwards for loop:

for(int i = ListOfTnAGroupAccs.Length -1; i >= 0; --i)
{
    var item = ListOfTnAGroupAccs[i];
    if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
    {
        ListOfTnAGroupAccs.Remove(item);
        continue;
    }
}
Ricardo Alves
  • 1,071
  • 18
  • 36
0

The way it occurs is that you are iterating over collection which you want to modify in a loop, which may break iteration.

The best approach is to loop backwards:

for(int i = ListOfTnAGroupAccs.Length - 1; i >= 0; i--)
  if(item.Prefix == "" && item.ReportingGrp == "" && item.AccMngInitials == "" && item.Description == "")
    ListOfTnAGroupAccs.RemoveAt(i);
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Use a for-loop instead of foreach.

for (int i = ListOfTnAGroupAccs.Count-1; i>=0; i--)
{
    if(ListOfTnAGroupAccs[i].Prefix == "" && ListOfTnAGroupAccs[i].ReportingGrp == "" && ListOfTnAGroupAccs[i].AccMngInitials == "" && ListOfTnAGroupAccs[i].Description == "")
    {
        ListOfTnAGroupAccs.RemoveAt(i);
        continue;
    }
}

We are going through the list in reverse order because we remove items. This way we prevent an IndexOutOfRangeException.

waka
  • 3,362
  • 9
  • 35
  • 54