Home > Software design >  List<T>.RemoveAll does not work on List objects
List<T>.RemoveAll does not work on List objects

Time:08-06

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 = "[email protected]" });

        var members = new List<Member>();
        members.Add(new Member { member = "[email protected]" });
        members.Add(new Member { member = "[email protected]" });

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

CodePudding user response:

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));
  • Related