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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With