Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List<T>.RemoveAll does not work on List objects

I have the below implementation.

members.RemoveAll doesn’t seem to be doing the job by the way. I wonder why and how to fix this. thanks!

public class Member
{
    public string member { get; set; }
}

public class SpecialMember
{
    public string Upn { get; set; }
}

public class RemoveFromList
{
    public static List<Member> Remove()
    {
        var specialMembers = new List<SpecialMember>();
        specialMembers.Add(new SpecialMember { Upn = "a@b.com" });

        var members = new List<Member>();
        members.Add(new Member { member = "a@b.com" });
        members.Add(new Member { member = "c@d.com" });

        var toRemove = members.Select(f => f.member)
                              .Intersect(specialMembers.Select(s => s.Upn))
                              .Select(m => new Member
                              {
                                  member = m
                              }).ToList();


        members.RemoveAll(m =>
        {
            var b = toRemove.Contains(m);
            return b;
        });

        return members;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you create new Member instances in the Select, so Object.ReferenceEquals doesn’t return true anymore and your Contains logic fails. You could simplify the whole code to:

members.RemoveAll(m => specialMembers.Select(sm => sm.Upn).Contains(m.member));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading