Search code examples
c#listremoveall

Remove from list items that have fields equal to some item fields


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.


Solution

  • 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:

    enter image description here

    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;
        }
    }