假设我有这个类:
public class Product
{
public string Id { get; set; }
public int Quantity { get; set; }
}
然后我有两个清单:
var oldList = new List<Product>(){
new Product(){
Id = "1", Quantity = 1
}
};
var newList = new List<Product>(){
new Product(){
Id = "1", Quantity = 5
}
};
如何比较这两个列表并返回newList
中已更改项目的单个Product对象。像上面的代码场景一样,我想返回一个值为Id = "1", Quantity = 5
的Product对象
另一种情况如下:
var oldList = new List<Product>(){
new Product(){
Id = "1", Quantity = 1
}
};
var newList = new List<Product>(){
new Product(){
Id = "1", Quantity = 1
},
new Product(){
Id = "2", Quantity = 1
}
};
如果newList
中添加了新项目,则我希望返回该项目(Id为"2"的产品对象)
你可以试试这样的东西:
var result = newList.Except(oldList);
但是您必须首先为Product
类实现IEquatable
接口。
public class Product : IEquatable<Product>
{
public string Id { get; set; }
public int Quantity { get; set; }
public bool Equals(Product product)
{
if (product == null)
{
return false;
}
return (Id == product.Id) && (Quantity == product.Quantity);
}
}
首先,您应该实现相等比较器来比较两个产品项是否相等:
class ProductEqualityComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.Id == y.Id && x.Quantity == y.Quantity;
}
public int GetHashCode(Product product)
{
if (Object.ReferenceEquals(product, null)) return 0;
return product.Id.GetHashCode() ^ product.Quantity.GetHashCode();
}
}
然后您可以使用Except
函数来获得两个列表之间的差异:
var result = newList.Except(oldList, new ProductEqualityComparer() );
一个变通方法,所以你不必使用Except,它是使用Linq对对象这样做的:
public List<MyItems> GetItemsFromANotInThatAreNotInB(List<MyItems> A, List<MyItems> B)
{
return (from b in B
where !(from a in A select a.Id).Contains(b.Id)
select b).ToList();
}