比较两个列表 - 如果一个列表中的任何对象 属性 已更改或列表中添加了新对象,则该对象 return

Compare two lists - If any objects property in one list have changed or a new object in list been added, return that object

假设我有这个 class:

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

我如何比较这两个列表和 return newList 中已更改的项目的单个产品对象。就像上面的代码场景一样,我想 return 一个具有值 Id = "1", Quantity = 5

的产品对象

另一个场景是这样的:

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 添加了新项目,那么我想 return 该项目(产品对象与 Id="2")

您可以尝试这样的操作:

var result = newList.Except(oldList);

但您必须首先为 Product class 实现 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);
    }
}

首先你应该实现相等比较器来比较 2 个产品项目是否相等:

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 to Object 来做到这一点,如下所示:

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