Firstly,i fill in the list with some objects with different propetries and afterwards I'd like to remove all inappropriate objects from this list. For sure, it throws an exception, saying that the list has been modified and it leads to problems with enumeration. How to manage this and remove all inappropriate objects without using another List, for example, ListFiltred, where I can add all appropriate objects?
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "01" });
MyList.Add(new Houses() { Number = "02" });
MyList.Add(new Houses() { Number = "04" });
MyList.Add(new Houses() { Number = "04" });
foreach (var item in MyList)
{
if (item.Number != "04")
{
MyList.Remove(item);
}
}
List<T> has a RemoveAll method that takes a predicate. You can use it like this:
MyList.RemoveAll(x=>x.Number != "04");
Use RemoveAll direct method
MyList.RemoveAll(val=>val.Number != "04");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With