我有三个列表,每个列表中包含三个相同的属性。我想将结果合并为一个集合。防爆班的结构如下
public class Order
{
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int OrderId { get; set; }
// Few other Properties of OrderDetail
}
public class PaymentDetail
{
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int OrderId { get; set; }
// Few other Properties form PaymentDetail
}
public class CouponUsageDetail
{
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int OrderId { get; set; }
// Few other Properties form CouponUsageDetail
}
这种类型的输出来自一个API服务,其中每个类都采用列表对象(JSON格式)的形式,我们需要对此执行一些操作。所有三个属性(ProductId,CustomerId,OrderId)在每个集合中包含相同的值,这意味着在每个集合中重复所有三个属性。我们需要对这些集合进行一些查找。因此,通常情况下,我们可以这样处理-从“订单”列表开始foreach并过滤PaymentDetail和CouponUsageDetail的所有三个匹配属性。但是,当数据大小增加时,在性能方面会更昂贵。因此,考虑将嵌套结构预先放置并避免查找。如果我们将输出嵌套如下,将有助于避免在PaymentDetail和CouponUsageDetail上查找。例-我们收到以下格式的JOSN
{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}
并通过此输出,我们希望将对象形成为
public class OrderDetails
{
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int OrderId { get; set; }
// Few other Properties of OrderDetail
List<PaymentDetail> PaymentDetail { get; set; }
List<CouponUsageDetail> CouponUsageDetail { get; set; }
}
您能指导linq的最佳最佳用法是什么,在这里我们可以将所有这三个匹配的属性组合在一起,并使它成为更好的嵌套结构?谢谢!注意:我知道此结构需要规范化,但是请忽略规范化规则,因为这不在我们的控制范围内。
您所描述的声音就像是两个标准的多键LINQ组联接一样。它们非常有效(LINQ to Objects实现使用准备好的基于快速哈希的查找),因此不需要进一步的优化:
var orderDetails = (
from o in data.Orders
join p in data.PaymentDetails
on new { o.ProductId, o.CustomerId, o.OrderId }
equals new { p.ProductId, p.CustomerId, p.OrderId }
into orderPaymentDetails
join c in data.CouponUsageDetails
on new { o.ProductId, o.CustomerId, o.OrderId }
equals new { c.ProductId, c.CustomerId, c.OrderId }
into orderCouponUsageDetails
select new OrderDetails
{
ProductId = o.ProductId,
CustomerId = o.CustomerId,
OrderId = o.OrderId,
// Few other Properties of OrderDetail
PaymentDetail = orderPaymentDetails.ToList(),
CouponUsageDetail = orderCouponUsageDetails.ToList(),
})
.ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句