我有一个由LINQ查询生成的匿名对象列表,我无权修改。
对象具有以下属性:
OrderId, RepId, FirstName, LastName, Address
每个" Rep"经常放置多个订单,因此有很多行,唯一的区别是OrderId。如果同一个Rep放置了多个订单,则需要将这些订单一起批处理为6个组,并使用新结构:
OrderId1, OrderId2, ..., OrderId6, RepId, FirstName, LastName, Address
但是如果代表已经发出了8个订单,则会有一批6个批次和2个批次2.因此新对象不会总是具有相同数量的属性。
我已经开始将RepId的初始结果分组,但我不知道下一步该去哪里。
这可以使用LINQ吗?
答案 0 :(得分:1)
由于您的输出具有不同模式的匿名对象,这使得事情变得更加复杂。
理想情况下,您应该将您的实体类设计为使用列表而不是像“OrderId1”,“OrderId2”这样的属性......这是不可扩展且容易出错的。但对于该特定问题,我们可以将LINQ和ExpandoObject结合起来实现这一目标。
orders.GroupBy(order => order.RepId)
.SelectMany(orderGroup => orderGroup.Select((order, i) => new {
Order = order,
ReqId = orderGroup.Key,
SubGroupId = i / 6
}))
.GroupBy(h => new {
ReqId = h.ReqId,
SubGroupId = h.SubGroupId,
FirstName = h.Order.FirstName,
LastName = h.Order.LastName,
Address = h.Order.Address
})
.Select(orderWithRichInfo => {
dynamic dynamicObject = new ExpandoObject();
int i = 1;
foreach(var o in orderWithRichInfo)
{
((IDictionary<string, object>)dynamicObject).Add("OrderId" + i, o.Order.OrderId);
i++;
}
((IDictionary<string, object>)dynamicObject).Add("FirstName", orderWithRichInfo.Key.FirstName);
((IDictionary<string, object>)dynamicObject).Add("LastName", orderWithRichInfo.Key.LastName);
((IDictionary<string, object>)dynamicObject).Add("Address", orderWithRichInfo.Key.Address);
return dynamicObject;
});
希望它有所帮助。
答案 1 :(得分:0)
如果您希望将6个OrderId-s作为列表,则可以创建
class OrderBundle
{
public int RepId { get; set; }
public List<int> OrderIds { get; set; }
}
将您的物品分组:
var orderBundels = orderList
.GroupBy(m => m.RepId)
.Select(g => new OrderBundle
{
RepId = g.Key,
OrderIds = g.Select(m => m.OrderId).ToList()
});
然后将它们分成几组:
List<OrderBundle> dividedOrderBundels = new List<OrderBundle>();
foreach (OrderBundle orderBundle in orderBundels)
{
int bundelCount = (int)Math.Ceiling(orderBundle.OrderIds.Count() / 6.0);
for (int i = 0; i < bundelCount; i++)
{
OrderBundle divided = new OrderBundle
{
RepId = orderBundle.RepId,
OrderIds = orderBundle.OrderIds.Skip(i * 6).Take(6).ToList()
};
dividedOrderBundels.Add(divided);
}
}
您可以在不创建如下模型的情况下获得相同的结果:
var result = orderList
.GroupBy(m => m.RepId)
.SelectMany(g => g.Select((m, i) => new
{
RepId = g.Key,
FirstName = m.FirstName,
LastName = m.LastName,
Address = m.Address,
OrderId = m.OrderId,
BunleIndex = i / 6
}))
.GroupBy(m => m.BunleIndex)
.Select(g => new
{
RepId = g.Select(m => m.RepId).First(),
FirstName = g.Select(m => m.FirstName).First(),
LastName = g.Select(m => m.LastName).First(),
Address = g.Select(m => m.Address).First(),
OrderIds = g.Select(m => m.OrderId).ToList()
})
.ToList()