简体   繁体   中英

Removing items found in another list

I have two lists and they are named: currentItems and newItems. newItems contains items found in currentItems and I am trying to those items before I output the list.

I have done some searching and I have tried using:

var newList = newItems.Except(CurrentItems).ToList();

but when I look at the output I still find the items from currentItems in the list. I found this example when I came across this question:

Quickest way to compare two List<>

which is similar to what I am trying to achieve but the all answers to the question do not work for me.

I have tried using:

List<ListItem> newList = newItems.Union(CurrentItems).ToList();

but I believe I am using it in the wrong situation since I am trying to remove the item completely from the list.

I have also tried looping through both loops, but I don't believe that is as efficient as it can be.

In the first example is there something I may be doing wrong with it? Or is there a different way to achieve my goal?

IEnumerable.Except will do what you want but it uses the default equality comparer. For custom objects you will need to implement Equals and GetHashCode

Also note that if newItems has duplicate values IEnumerable.Except will also do a distinct on your list.

EDIT2: You need an equality comparer that compares ListItem's I believe.

You'll need to pass in a custom comparor that compares just the Value property of the ListItem .

var newList = newItems.Except(currentItems, new ListItemValueComparer());

And the custom equality comparer is here...

class ListItemValueComparer : IEqualityComparer<ListItem>
{
    public bool Equals(ListItem x, ListItem y)
    {
        return x.Value.Equals(y.Value);
    }

    public int GetHashCode(ListItem obj)
    {
        return obj.Value.GetHashCode();
    }
}

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