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

时间:2015-02-17 15:43:30

标签: c# linq list compare

假设我有这门课程:

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-object。与上面的代码场景一样,我想返回值为Id = "1", Quantity = 5

的Product-object

另一种情况如下:

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”的产品对象)

3 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

var result = newList.Except(oldList);

但您首先要为IEquatable类实现Product接口。

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

答案 1 :(得分:1)

首先,您应该实现相等比较器来比较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() );

答案 2 :(得分:0)

一种解决方法,所以你不必使用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();
}