我正在从两个不同的API调用获取数据。一个得到我";客户";数据和另一个"数据";城镇;数据每个客户都有一个城镇引用,所以在我的应用程序中,我需要由客户对象引用实际的城镇对象。以下是我的类的一个大大简化的表示:
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; }
}
我能想到实现我的目标的唯一方法如下(假设我实际上是从我的API调用中获得列表,下面只是为了解释问题(:
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();
}
这感觉不是实现我目标的有效方式,尤其是当我有几十个其他地方需要做同样的事情时。
根据注释编写时,您使用的是原始Customer
对象,而没有将Town
分配给town
属性。
应该是:
对于查询表达式
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();
对于方法表达式
customers = customers
.Join(towns,
x => x.townId,
x => x.townId,
(x, y) =>
{
var customer = x;
customer.town = y;
return customer;
})
.ToList();
使用联接:
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());
因此调用了这两个API之后。添加到客户对象时
您可以执行以下操作,
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
});
现在,您可以访问与客户对应的城镇,而无需任何加入。此外,有多种方法可以有效地做到这一点。我更喜欢这种方式。如果你有任何疑问,请告诉我。