Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove multiple items in List using RemoveAll on condition?

I tried like following.

MyList.RemoveAll(t => t.Name == "ABS");
MyList.RemoveAll(t => t.Name == "XYZ");
MyList.RemoveAll(t => t.Name == "APO");

Instead how can I do something like:

MyList.RemoveAll(t => t.Name == "ABS" || t => t.Name == "XYZ" ||t => t.Name == "APO");
like image 811
Neo Avatar asked Jul 16 '14 12:07

Neo


People also ask

How do I remove multiple data from a list?

Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.

Can you remove multiple values in list python?

Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values.

Which function is used to delete multiple elements of a list?

For removing multiple elements from a list by index range we can use del operator.


4 Answers

You only need one lambda expression - the || goes within that:

MyList.RemoveAll(t => t.Name == "ABS" || t.Name == "XYZ" || t.Name == "APO");

In other words, "Given a t, I want to remove the element if t.Name is ABS, or if t.Name is XYZ, or if t.Name is APO."

There's only one "given a t" in there, which is what the t => part means, effectively.

like image 55
Jon Skeet Avatar answered Nov 15 '22 21:11

Jon Skeet


A more extnsible approach would be to have a List for what to remove then

List<T> toRemove = ...
MyList.RemoveAll(t =>  toRemove.Contains(t.Name));

where T is a string in your example

like image 23
MikeW Avatar answered Nov 15 '22 19:11

MikeW


If it's not required at any time that there are multiple items in the list, you should consider using a HashSet instead of List

like image 44
Norman Avatar answered Nov 15 '22 19:11

Norman


or

var nameToRemove = new[]{"ABS", "XYZ", "APO"};
MyList.RemoveAll(t => nameToRemove.Contains(t.Name))
like image 29
Raphaël Althaus Avatar answered Nov 15 '22 21:11

Raphaël Althaus