我试图比较两个包含复杂对象的c#列表。我知道之前已经提出了类似的问题,但这有点不同。 我按照MSDN示例写了这封信:https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx
public class ProductA
{
public string Name { get; set; }
public int Code { get; set; }
}
public class ProductComparer : IEqualityComparer<ProductA>
{
public bool Equals(ProductA x, ProductA y)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether the products' properties are equal.
return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
}
public int GetHashCode(ProductA obj)
{
//Get hash code for the Name field if it is not null.
int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = obj.Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
然后使用Except方法删除&#34; apple&#34;列表中的9
ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 },
new ProductA { Name = "orange", Code = 4 },
new ProductA { Name = "lemon", Code = 12 } };
ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } };
//Get all the elements from the first array //except for the elements from the second array.
IEnumerable<ProductA> except = fruits1.Except(fruits2);
foreach (var product in except)
Console.WriteLine(product.Name + " " + product.Code);
此代码应生成以下输出: 橙子4柠檬12
我没有并打印出以下内容: 苹果9橙4柠檬12
答案 0 :(得分:4)
MSDN文档中似乎出现错误:https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx
Except方法调用应该使用IEqualityComparer:
//Get all the elements from the first array //except for the elements from the second array.
ProductComparer pc = new ProductComparer();
IEnumerable<ProductA> except = fruits1.Except(fruits2, pc);