简体   繁体   English

删除在另一个列表中找到的项目

[英]Removing items found in another list

I have two lists and they are named: currentItems and newItems. 我有两个列表,它们分别命名为:currentItems和newItems。 newItems contains items found in currentItems and I am trying to those items before I output the list. newItems包含在currentItems中找到的项目,在输出列表之前,我尝试使用这些项目。

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. 但是当我查看输出时,仍然可以从列表中的currentItems中找到项目。 I found this example when I came across this question: 当我遇到这个问题时,我找到了这个例子:

Quickest way to compare two List<> 比较两个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. IEnumerable.Except将做您想要的,但是它使用默认的相等比较器。 For custom objects you will need to implement Equals and GetHashCode 对于自定义对象,您将需要实现EqualsGetHashCode

Also note that if newItems has duplicate values IEnumerable.Except will also do a distinct on your list. 还要注意,如果newItems具有重复的值IEnumerable.Except也会在您的列表上做不同的事情。

EDIT2: You need an equality comparer that compares ListItem's I believe. EDIT2:您需要一个相等比较器来比较ListItem的可信度。

You'll need to pass in a custom comparor that compares just the Value property of the ListItem . 您需要传入一个自定义比较器,该比较器仅比较ListItemValue属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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