Question

I am trying to compare the contents of a number of Tuples inside of a List. The code runs reasonable well, but on certain occasions, completeList[z].Item1.Count will come back with the wrong number. When I look in the debugger, in one example a = completeList[z].Item1.Count might return 18 when the count is 9. So this causes it to go out of range.

completeList.Count returns correctly, as does completeList[z].Item1[b], so I'm not sure what I could be doing wrong with completeList[z].Item1.Count.

Thanks for any insights!

int x = completeList.Count;
int y = 0;
while (y < x)
{
 for (int z = 0; z < x; z++)
 {
  if (y != z && completeList[y].Item6.Equals(completeList[z].Item6))
  {
   int a = completeList[z].Item1.Count;
   a = a -1;
   for (int b = 0; b < a; b++)
   {
    if (completeList[y].Item1.Contains(completeList[z].Item1[b]))
    {
     completeList[z].Item1.RemoveAt(b);
     completeList[z].Item2.RemoveAt(b);
     completeList[z].Item3.RemoveAt(b);
     completeList[z].Item4.RemoveAt(b);
     completeList[z].Item5.RemoveAt(b);
    }
   }
  }
 }
 y++;
}
Was it helpful?

Solution

You're removing items from the list. This is changing the count, and also moving around the indexes of the existing items. The count is correct at the start of the loop, but by the time you've actually removed an item, the count is no longer valid.

The most effective solution is to not iterate the list while removing items at all; instead rely on the list's RemoveAll method to remove all of the items that match your list of items to remove. While it's possible for you to manage the indexes properly to remove while iterating, you should avoid this complexity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top