0

Problem throwing this Exception:

System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

foreach(var string in list)
{ if condition true;
remove element from list;
work for remaining list items; // Exception

Do anyone of you have solution to this issue?

Don't want answer like:

move items into new list and then remove all together. use for or something else

Dummy Code:

public List<Tuple<int, string, string>> OpM(List<Tuple<int, string, string>> tuple)
        {
        foreach (var v in tuple)
        {
        cal = (swl * 100) / iwl;
                        if (cal <= sf)
                        {
                            st = st + " " + v.Item3;
                            Console.WriteLine("Added: {0}", st);
                            tuple.Remove(v);
        }
    else {continue;}
        }
}
return tuple;
}

THANK YOU SO MUCH! I got the answer.

foreach (var v in tuple.ToList())
       { tuple.Remove(v);  }

But I also want to know that how to use these two way:

1- List.Distinct()
2- LINQ: list = list.Where(a => !condition);
Nab
  • 61
  • 2
  • 10
  • try out distince function List.Distinct();....that will do work for you – Pranay Rana Nov 21 '17 at 06:03
  • If the question is duplicate so the reason is answer isn't found in any post that are resembling it as duplicate. – Nab Nov 21 '17 at 06:05
  • Please show me use of distinct by taking any code as dummy. So I get to know how properly I can use distinct. – Nab Nov 21 '17 at 06:06
  • The duplicate answer is pretty old. These days you can just use LINQ: `list = list.Where(a => !condition);` – John Wu Nov 21 '17 at 06:08
  • @JohnWu Please use it by using dummy code. – Nab Nov 21 '17 at 06:10
  • Also, `IEnumerable`/collection types should use a plural name, like `tuples`. – Rufus L Nov 21 '17 at 06:30
  • (oops, deleted this accidentally) In your dummy code, there is no need to remove items from the list, since there is no side effect to having them there. You can just call `tuple.Clear()` after your loop body. Also, the loop should be inside the `if (cal <= sf)` statement, since the loop does not affect the condition, you are needlessly calculating that over and over again. – Rufus L Nov 21 '17 at 06:40
  • You dummy code would be: `if ((swl * 100) / iwl <= sf) { foreach (var tuple in tuples) { st += $" {v.Item3}"; Console.WriteLine($"Added: {st}"); } tuples.Clear(); }` – Rufus L Nov 21 '17 at 06:45
  • It's not real code, I just added it for others to give solution on that dummy code.@RufusL I want to remove only those items that satisfying condition. List should have other items in it. While tuples.Clear() will empty the whole list. – Nab Nov 21 '17 at 07:02
  • @JohnWu I used this: tuple.RemoveAll(f => f.Equals(cal <= sf)); Is it correct? – Nab Nov 21 '17 at 07:39

0 Answers0