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.
CodePudding user response:
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();
CodePudding user response:
Use a join :
var results = (from c in customers
join t in towns on c.townId equals t.townId
select new { customer = c, town = t}
).GroupBy(x => x.customer.Name)
.ToDictionary(x => x.Key, y => y.First());
CodePudding user response:
After you are calling the 2 APIs consequently. While adding to the Customer Object.
You can do following,
customers.Add(new Customer
{
Id = cSerializedApiObj.Id,
Name = cSerializedApiObj.Name,
town = tSerializedAPiObjList.
FirstorDefault
(x=>x.townId==cSerializedApiObj.townId)
townId=town.townId //it isn't required anymore
});
Now you can access the town corresponding to the customer without any joining. Also, there can be multiple ways to do this efficiently. I prefer this way. Let me know if u have any queries.