Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists with Except method

Tags:

c#

I'm trying to compare two lists with the Except method but it doesn't work correct:

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>();
}

The result of the variable "result" should be all records of "PotentialSharedCustomers", there are not in the list "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" });

I thougt "Except" is the correct way to solve this, but I get the return of all items of "PotentialSharedCustomer"

Thx for help

like image 756
Patrik Avatar asked Oct 15 '13 13:10

Patrik


Video Answer


1 Answers

One way without overriding Equals or writing a custom IEqualityComparer is to get a list of identifiers and then filter your list:

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

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

You could look at other data structures like HashSet to improve the lookup performance but if the size is small this may be sufficient.

like image 83
D Stanley Avatar answered Oct 05 '22 04:10

D Stanley