簡體   English   中英

如果我不能直接修改類,如何使用元素類型的字段值從另一個列表中刪除列表?

[英]How can I remove a list from another list using a field value of the element's type if i can't modify the class directly?

假設我有一個List<Product>bigList<Product> ,該對象的某些對象Product具有2個字段IDName 該列表已完全填充,這意味着每個元素都具有兩個不為null字段,盡管可以。

我還有另一個List<Product> ,它小於第一個,名為small ,但是這次某些元素的字段Namenull ,而ID始終存在。

我想從ID相同的big中刪除small

例:

List<Product> big = { {1,A},{2,B},{3,C},{4,D} };
List<Product> small = { {1,null},{3,C} };
List<Product> result = { {2,B},{4,D}};

我無法修改Product對象,即無法實現IEquatable<Product> ,並且此類接口未實現,這意味着big.Except(small)big.RemoveAll(small)big.Contains(anElementOfSmall)將無法正常工作(出於疑問,我已經嘗試過了)。

我想避免使用刪除迭代器或類似方法的雙循環,我在搜索帶有特定謂詞的內置函數。

使用簡單的謂詞,您可以輕松實現:

big.Where(p => !small.Any(o => o.id == p.id)).ToList();

轉換為:從big元素中選擇( p )不能滿足其中small元素o具有相同ID

為您的產品實現IEqualityComparer ,以根據ID比較兩個Product 然后只需使用Except並通過比較器即可:

var result = big.Except(small, new ProductComparer()).ToList();

您需要告訴Except如何比較Product實例。

public class ProductEqualityComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        //they're both the same instance or they're both null
        if(ReferanceEquals(x, y))
            return true;

        //only one of them is null
        if(x == null || y == null)
            return false;

        return x.Id == y.Id;
    }

    public int GetHashCode(Product prod)
    {
        return prod == null? 0 : prod.Id.GetHashCode();
    }
}


big.Except(small, new ProductEqualityComparer())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM