使用Except方法比较两个列表

时间:2013-10-15 13:58:53

标签: c#

我正在尝试使用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”所有项目的回报

寻求帮助

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:2)

Customer应该实施IEquatable<Customer>,这意味着您必须实施public bool Equals(Customer other)(如果other等于this则返回true)和{{ 1}}。

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

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

答案 2 :(得分:0)

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