简体   繁体   中英

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

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.

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...

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM