因此,您要获取所有新客户和所有不在新列表中的旧客户:
List<Customer> customers = NewCustomers.Concat(OldCustomers.Except(NewCustomers)).ToList();
请记住实现IEqualityComparer<T>
通用接口来比较您的客户(可能通过CustomerID
)。GetHashCode
因此,您需要Equals
为Customer
.
这是一个可能的实现:
public class Customer
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public override bool Equals(Object obj)
{
Customer cust = obj as Customer;
if (cust == null) return false;
return cust.CustomerID == CustomerID;
}
public override int GetHashCode()
{
return CustomerID.GetHashCode();
}
public class Comparer : IEqualityComparer<Customer>
{
public bool Equals(Customer x, Customer y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.Equals(y);
}
public int GetHashCode(Customer obj)
{
if (obj == null) return -1;
return obj.GetHashCode();
}
}
}
请注意,我覆盖Equals
和GetHashCode
在Customer
. 通过这种方式,您甚至不需要传递 to 的实例IEqualityComparer<Customer>
(Except
或任何其他允许传递比较器的方法)。
但为了完整起见,我还添加了Comparer
实现接口的类,因此您也可以将其传递给 except:
NewCustomers.Concat(OldCustomers.Except(NewCustomers, new Customer.Comparer()));