Here is my code:
public class Person
{
public int age;
public int grade;
public string name;
}
List<Person> _list = new List<Person>();
// .... add lots of items
var personToRemove = new Person {age = 99, grade = 7, };
How to write a command that removes from _list all persons what have the same age and grade values that personToRemove has.
You have to use .RemoveAll() with predicate to remove all persons with matching details in personToRemove person object.
So your query will be.
int totalRemoved = _list.RemoveAll(x => x.age == personToRemove.age && x.grade == personToRemove.grade);
Input:
_list.Add(new Person { age = 99, grade = 7 });
_list.Add(new Person { age = 87, grade = 7 });
_list.Add(new Person { age = 57, grade = 8 });
Output:

Edit:
You can also use traditional looping for elegant way to remove match person from list of persons.
for (int i = _list.Count - 1; i >= 0; i--)
{
if (_list[i].age == personToRemove.age && _list[i].grade == personToRemove.grade)
{
_list.RemoveAt(i);
break;
}
}
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