1
我有以下的扁平結構:集結訂單行成一個訂單彙總 - 如何獲得數量
Name1 | Name2 | Price | SubName | SubPrice
------+-------+-------+---------+---------
A | one | 10 | X | 5
A | one | 10 | Y | 7
A | one | 10 | Z | 11
A | one | 10 | X | 5
A | one | 10 | Y | 7
A | one | 10 | Z | 11
A | two | 16 | X | 5
A | null | 9 | null | null
B | three | 24 | null | null
它需要被轉化爲以下幾點:
{
0 = {
Name = "A one X, Y, Z",
Quantity = 2,
TotalPrice = 66,
},
1 = {
Name = "A two X",
Quantity = 1,
TotalPrice = 21,
},
2 = {
Name = "A",
Quantity = 1,
TotalPrice = 9,
},
3 = {
Name = "B three",
Quantity = 1,
TotalPrice = 24,
}
}
的理論很簡單 - .GroupBy()
Name1和Name2 - 問題是,一旦我得到.Select()
從組中,我永遠不能得到正確的數量...我知道這應該是簡單的,但我似乎無法琢磨它...
items
.GroupBy(item => new
{
item.Name1,
item.Name2,
})
.Select(grouping => new
{
Name = grouping.Key.Name1 + " " + grouping.Key.Name2,
Price = grouping.Key.Price,
Subs = grouping.GroupBy(groupItem => new
{
groupItem.SubName,
groupItem.SubPrice,
}),
})
.Select(temp => new
{
Name = temp.Name + (temp.Subs.Any() ? " " + temp.Subs.Select(sub => sub.SubName).Aggregate((a, b) => (a + ", " + b)) : string.Empty),
FullItemPrice = temp.Price + temp.Subs.Sum(subPrice => subPrice ?? 0m),
Quantity = ???,
})
.Select(output => new
{
output.Name,
output.Quantity,
TotalPrice = output.FullItemPrice * output.Quantity,
});
如何計算所需結果中的TotalPrice? – MarcinJuraszek
FullItemPrice =價格+(SubPrices的總和)。因此,對於A,10 +(5 + 7 + 11)= 33,並且有2個A,所以TotalPrice = 33 * 2 = 66 –