使用“除外”方法比较两个列表

本文关键字:两个 列表 比较 除外 方法 使用 | 更新日期: 2023-09-27 18:35:39

我正在尝试使用 Except 方法比较两个列表,但它无法正常工作:

List<Customer> PotentialSharedCustomer = new List<Customer>();
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "01234", Name = "Hans Jürgen" });
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "05465", Name = "Beate Müller" });
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "15645", Name = "Sabine Meyer" });
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "54654", Name = "Moritz Kummerfeld" });
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "15647", Name = "Hanna Testname" });
List<Customer> ActualSharedCustomer = new List<Customer>();
ActualSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "01234", Name = "Hans Jürgen" });
ActualSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "05465", Name = "Beate Müller" });
ActualSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "15645", Name = "Sabine Meyer" });
PrepareCreateSharedCustomer(PotentialSharedCustomer, ActualSharedCustomer);
public void PrepareCreateSharedCustomer(List<Customer> potentialSharedCustomer, List<Customer> actualSharedCustomer)
{
    List<Customer> result = potentialSharedCustomer.Except(actualSharedCustomer).ToList<Customer>();
}

变量"result"的结果应该是"PotentialSharedCustomers"的所有记录,列表中没有"ActialSharedCustomer":

PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "54654", Name = "Moritz Kummerfeld" });
PotentialSharedCustomer.Add(new Customer { AccountId = Guid.Empty, AccountNumber = "15647", Name = "Hanna Testname" });

我认为"除了"是解决此问题的正确方法,但是我得到了"潜在共享客户"所有项目的退货

感谢帮助

使用“除外”方法比较两个列表

不覆盖Equals或编写自定义IEqualityComparer的一种方法是获取标识符列表,然后过滤列表:

List<string> accountNumbers = 
    potentialSharedCustomer.Select(c => c.AccountNumber)
                           .Except(actualSharedCustomer.Select(c => c.AccountNumber));
List<Customer> result = potentialSharedCustomer.Where(c => accountNumbers.Contains(c.AccountNumber));

您可以查看其他数据结构(如HashSet)以提高查找性能,但如果大小较小,这可能就足够了。

Customer应该实现IEquatable<Customer>,这意味着你必须实现public bool Equals(Customer other)(如果other等于this,则返回true)和public int GetHashCode()

查看文档以获取示例:http://msdn.microsoft.com/en-us/library/bb300779.aspx

还有另一个StackOverflow答案,它举例说明了如何进行GetHashCode()实现:https://stackoverflow.com/a/263416/62802。

var distinctCustomer = PotentialSharedCustomer
    .Select(p => p.AccountNumber)
    .Except(actualSharedCustomer.Select(q => q.AccountNumber))
    .ToList();