我正在尝试使用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>();
}
Run Code Online (Sandbox Code Playgroud)
变量"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" });
Run Code Online (Sandbox Code Playgroud)
我认为"除了"是解决这个问题的正确方法,但我得到了"PotentialSharedCustomer"所有项目的回报
谢谢你的帮助
不覆盖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));
Run Code Online (Sandbox Code Playgroud)
您可以查看其他数据结构,HashSet以提高查找性能,但如果大小很小,这可能就足够了.