Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering inside the List [duplicate]

Tags:

c#

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);
    }
}
like image 635
David Shepard Avatar asked Apr 30 '26 18:04

David Shepard


2 Answers

List<T> has a RemoveAll method that takes a predicate. You can use it like this:

MyList.RemoveAll(x=>x.Number != "04");
like image 57
Chris Avatar answered May 03 '26 06:05

Chris


Use RemoveAll direct method

MyList.RemoveAll(val=>val.Number != "04");
like image 34
Sajeetharan Avatar answered May 03 '26 07:05

Sajeetharan