[英]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>
為big
的List<Product>
,該對象的某些對象Product
具有2個字段ID
和Name
。 該列表已完全填充,這意味着每個元素都具有兩個不為null
字段,盡管可以。
我還有另一個List<Product>
,它小於第一個,名為small
,但是這次某些元素的字段Name
為null
,而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.