I am getting data from two different API calls. One gets me "customer" data, the other "towns" data. Each customer has a town reference, so in my application, I need to have the actual town object referenced by the customer object. Here is a vastly simplified representation of my classes:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int townId { get; set; }
public Town town { get; set; }
}
public class Town
{
public int townId { get; set; }
public string townName { get; set; }
}
The only way I can think of achieving my objective is as follows (assume I am actually getting the lists from my API calls, the following is just for sake of explanation of the problem):
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 1, Name = "First Customer", townId = 10 });
customers.Add(new Customer { Id = 2, Name = "Second Customer", townId = 20 });
customers.Add(new Customer { Id = 2, Name = "Third Customer", townId = 20 });
List<Town> towns = new List<Town>();
towns.Add(new Town { townId = 10, townName = "Eton" });
towns. Add(new Town { townId = 20, townName = "Harrow" });
towns.Add(new Town { townId = 30, townName = "Cambridge" });
foreach(Customer c in customers)
{
c.town = towns.Where(t => t.townId == c.townId).FirstOrDefault();
}
This does not feel like an efficient way of achieving my objective, especially when I have dozens of other places I would need to do the same sort of thing.
>Solution :
As written according to your comment, you are using the original Customer object without assigning Town to the town property.
It should be:
For query expression
customers = (from a in customers
join b in towns on a.townId equals b.townId
select new Customer
{
Id = a.Id,
Name = a.Name,
townId = a.townId,
town = b
})
.ToList();
For method expression
customers = customers
.Join(towns,
x => x.townId,
x => x.townId,
(x, y) =>
{
var customer = x;
customer.town = y;
return customer;
})
.ToList();