Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

removeall

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.

like image 737
Narek Avatar asked Jan 31 '26 23:01

Narek


1 Answers

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;
    }
}
like image 88
er-sho Avatar answered Feb 03 '26 13:02

er-sho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!