【问题标题】:Compare two lists - If any objects property in one list have changed or a new object in list been added, return that object比较两个列表 - 如果一个列表中的任何对象属性已更改或列表中添加了新对象,则返回该对象
【发布时间】:2015-04-18 08:56:17
【问题描述】:

假设我有这个课程:

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

另一个场景是这样的:

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 diffList = oldList.Where(o =&gt; !newList.Any(n =&gt; n.Id == o.Id)) .Union(newList.Where(n =&gt; !oldList.Any(o =&gt; n.Id == o.Id)));?

标签: c# linq list compare


【解决方案1】:

你可以试试这样的:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      一种解决方法,因此您不必使用除了使用 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        相关资源
        最近更新 更多