给出以下示例类:
public class OrderHeader
{
public int OrderHeaderId { get; set; }
public string CustomerName { get; set; }
}
public class OrderItem
{
public int OrderHeaderId { get; set; }
public int OrderItemId { get; set; }
public string ProductName { get; set; }
public float Price { get; set; }
}
// Order contains the header information and a collection of items ordered
public class Order
{
public OrderHeader Header { get; set; }
public IEnumerable<OrderItem> Items { get; set; }
}
// LineItem is OrderHeader and OrderItem flattened out
public class LineItem
{
public int OrderHeaderId { get; set; }
public int OrderItemId { get; set; }
public string CustomerName { get; set; }
public string ProductName { get; set; }
public float Price { get; set; }
}
使用jgauffin to extend ValueInjector中的扩展方法来处理集合,以下内容将Order
的集合展平为LineItem
的集合:
var orders = new List<Order>();
var lineItems = new List<LineItem>();
// -extension method for collections with ValueInjector
// -project all the OrderItems into a single list
lineItems.InjectFrom( orders.SelectMany( x => x.Items ) );
// inject the header information into the flattened out LineItem objects
foreach( LineItem item in lineItems )
{
var order = orders.Single( x => x.Header.OrderHeaderId == item.OrderHeaderId );
item.InjectFrom( order.Header );
}
2个问题:
Order
的集合展平为LineItem
的集合?如果没有,会有什么替代方案? (除了不使用ValueInjector扩展方法,只使用一个单独的每个循环将Header和OrderItem注入到展平的LineItem中)