在下面的代码中,我有一个代表订单的对象列表Line
。由于订单可以包含多个产品,因此我可以按订单号对这些对象进行分组。下面的代码按订单号对所有行对象进行分组,我创建了一个名为ServiceOrder
的对象实例。 ServiceOrder
有订单号,我将该订单的所有产品绑定到List<Line>
。
在我的代码中,它是一个两步过程,我首先对所有Line
个对象进行分组,然后迭代该组以创建List<ServiceOrder>
个对象。
使用linq,可以使用1行语句完成,例如一步?
输出
Order: A1234
1. Widget 2
2. Sproket 2
3. Wobble 2
代码:
Line o1 = new Line { OrderNumber = "A1234", Description = "Widget", Qty = 2 };
Line o2 = new Line { OrderNumber = "A1234", Description = "Sproket", Qty = 2 };
Line o3 = new Line { OrderNumber = "A1234", Description = "Wobble", Qty = 2 };
Line o4 = new Line { OrderNumber = "A98745", Description = "Cog", Qty = 2 };
List<Line> incomingOrders = new List<Line>();
incomingOrders.Add(o1);
incomingOrders.Add(o2);
incomingOrders.Add(o3);
incomingOrders.Add(o4);
List<ServiceOrder> serviceOrders = new List<ServiceOrder>();
var orderGrouped = incomingOrders.Select((value, index) => new { obj = value, idx = index })
.GroupBy(order => order.obj.OrderNumber).Select(grp => grp.Select(g => g.obj).ToList()).ToList();
foreach (var grp in orderGrouped)
{
ServiceOrder serviceOrder = new ServiceOrder();
var firstOrder = grp.First();
serviceOrder.OrderNumber = firstOrder.OrderNumber;
serviceOrder.Orders = grp;
serviceOrders.Add(serviceOrder);
}
// print out
foreach (var order in serviceOrders) {
System.Diagnostics.Debug.WriteLine("Order: " + order.OrderNumber);
int num = 1;
foreach (var line in order.Orders) {
System.Diagnostics.Debug.WriteLine(String.Format("{0}. {1} {2}", num, line.Description, line.Qty));
num++;
}
}
public class ServiceOrder
{
public List<Line> Orders { get; set; }
public String OrderNumber { get; set; }
}
public class Line {
public int Qty { get; set; }
public String Description { get; set; }
public String OrderNumber { get; set; }
}
答案 0 :(得分:3)
使用IGrouping.Key
属性:
List<ServiceOrder> serviceOrders =
incomingOrders.GroupBy(o => o.OrderNumber)
.ToList(g => new ServiceOrder() {
OrderNumber = g.Key,
Orders = g.ToList() });
PS。当你以后根本没有使用它时,为什么要在你的枚举中引入索引?