7

我正在尝试将两个列表与 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" });

我认为“除外”是解决此问题的正确方法,但我得到了“PotentialSharedCustomer”的所有项目的退货

谢谢帮助

4

3 回答 3

9

一种不覆盖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提高查找性能,但如果大小很小,这可能就足够了。

于 2013-10-15T14:06:19.290 回答
2

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

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

还有其他 StackOverflow 答案示例了如何GetHashCode()实现:https ://stackoverflow.com/a/263416/62802 。

于 2013-10-15T14:07:30.597 回答
1
var distinctCustomer = PotentialSharedCustomer
    .Select(p => p.AccountNumber)
    .Except(actualSharedCustomer.Select(q => q.AccountNumber))
    .ToList();
于 2015-04-02T09:48:46.930 回答