You cannot use foreach to remove elements at enumeration, you get an exception at runtime.
You can use List.RemoveAll :
list.RemoveAll(x => x.Number == 1);
or, if itβs actually not a List<T> , but any sequence, LINQ:
list = list.Where(x => x.Number != 1).ToList();
If you are sure that there is only one element with this number or you want to remove one maximum element, you can either use the for loop approach suggested in another answer, or this:
var item = list.FirstOrDefault(x => x.Number == 1); if(item ! = null) list.Remove(item);
A link to another question that I posted suggests that you change the collection while listing in C # 4 and later. No, you can not. This applies only to new parallel collections .
Tim schmelter
source share