Coderz
Coderz

Reputation: 245

Difficulty in Removing Items From List?

I have two lists. The first is of all students and the second is of selected students. I want if I one time select some student they will remove from the all-student list. Here is my code but it doesn't. Students won't get removed.

foreach (var li in ListSelectedStudents.ToList())
{
    if (ListAllStudents.Contains(li))
    {
        ListAllStudents.Remove(li);
    }
}

Upvotes: 0

Views: 133

Answers (3)

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

Contains will use equality to determine what is "equal", I am assuming here that your custom class hasn't provided a custom equality implementation, which means the default equatable will be provided for that type and it's just using reference equality. So even though you think two things are "equal", the Contains method doesn't and so doesn't step into the Remove call.

To get that particular code to behave what you need to do is provide an implementation of IEquatable<Student> on the Student class, as described in the remarks here.

In this instance, Contains isn't actually required as Remove will do the same checks. If there is nothing to remove, the Remove call will be transparent, effectively doing nothing.

As has been caught in the comments before I had chance to provide the information, Remove will also rely on IEquatable<Student> (docs) so you still need to provide an implementation, but it will make your code look a little cleaner:

foreach (var li in ListSelectedStudents.ToList())
{
    ListAllStudents.Remove(li);
}

There may be various ways to do this without the need to implement the interface, but you won't be able to use your current code for it. I'll leave other answers to field those alternatives as it's Friday and my brain is not yet functioning properly.

Upvotes: 4

Ankush Madankar
Ankush Madankar

Reputation: 3834

Try this:

ListSelectedStudents = ListSelectedStudents.Where(a => !ListSelectedStudents.Contains(a)).Select(a => a).ToList();

Upvotes: 0

Rex
Rex

Reputation: 2140

have you tried using linq:

ListAllStudents.RemoveAll(m => ListSelectedStudents.Contains(m));

if it does not work, it could be something wrong with the default comparison implemented in the object, and you could either fix the comparer, or do something like:

ListAllStudents.RemoveAll(m => ListSelectedStudents.Any(n=>n.Id == m.Id)); // Assume the Id is the primary key of the object...

Upvotes: 3

Related Questions