My main object is a list of customers. Because of the way I have to obtain the data I have two lists I need to merge as shown below. The balances list includes the balances for all customers. Basically I want to add the balances associated with a particular customer to the customers list. I'm trying to use Linq to merge the two based on their common key of CustomerNumber, but haven't been able to make it work.
List<Customer> customers
List<Balance> balances
public class Customer
{
int CustomerNumber {get;set;}
List<Balance> Balances{get;set;}
}
public class Balance
{
int CustomerNumber {get;set;}
decimal Amount {get;set;}
}
So lets save I have this list of customers
List<Customer> customers = new List<Customer>{
new Customer {CustomerNumber = 1},
new Customer {CustomerNumber = 2},
new Customer {CustomerNumber = 3}
};
And this list of balances
List<Balance> balances = new List<Balance>{
new Balance {Amount = 10, CustomerNumber = 1},
new Balance {Amount = 20, CustomerNumber = 1},
new Balance {Amount = 30, CustomerNumber = 2},
new Balance {Amount = 80, CustomerNumber = 2},
new Balance {Amount = 100, CustomerNumber = 2},
new Balance {Amount = 50, CustomerNumber = 3},
};
In the end I would have
- Customer 1 would have a list with the 10 and 20 amounts
- Customer 2 would have a list with the 30, 80, and 100 amounts
- Customer 3 would have a list with the 50 amount.
The current solution looks like:
foreach (var customer in customers)
{
var matchingBalances = balances
.Where(x => x.CustomerNumber == customer.CustomerNumber);
customer.Balances.AddRange(matchingBalances);
}
Update: Here's what I ended up using.
var merge2 = customers.GroupJoin(balances,
c => c.CustomerNumber,
b => b.CustomerNumber,
(c, b) =>
{
c.Balances = b.ToList()
return c;
});

GroupJoinsolution below too, this might also help.