【发布时间】:2019-12-27 22:18:28
【问题描述】:
假设我有这样的课程:
public class Transaction
{
public string PointOfSale { get; set; }
public List<PurchaseItem> PurchaseItems { get; set; }
public decimal Cost { get; set; }
}
public class PurchaseItem
{
public ItemType Type { get; set; } //ItemType is an enum
public string Subtype { get; set; }
}
我想做的是根据交易的地点和购买的物品对交易进行分组,并总结成本。
我觉得GroupBy() 将是这里的解决方案,但我不知道如何让它比较 PurchaseItems 作为键的一部分,因为 PurchaseItem 是一个引用类型,并指定一个 IEqualityComparer到GroupBy() 必须能够比较整个密钥。
例如:
Transaction[] transactions =
{
new Transaction
{
PointOfSale = "Bytes-R-Us",
PurchaseItems = new List<PurchaseItem>
{
new PurchaseItem { ItemType = ItemType.Electronics, Subtype = "peripherals" },
new PurchaseItem { ItemType = ItemType.Food, Subtype = "candy" }
},
Cost = 50.00
},
new Transaction
{
PointOfSale = "Bytes-R-Us",
PurchaseItems = new List<PurchaseItem>
{
new PurchaseItem { ItemType = ItemType.Electronics, Subtype = "peripherals" },
new PurchaseItem { ItemType = ItemType.Food, Subtype = "candy" }
},
Cost = 25.00
},
new Transaction
{
PointOfSale = "Bytes-R-Us",
PurchaseItems = new List<PurchaseItem>
{
new PurchaseItem { ItemType = ItemType.Software, Subtype = "games" }
},
Cost = 100.00
},
new Transaction
{
PointOfSale = "The Foo Bar & Grill",
PurchaseItems = new List<PurchaseItem>
{
new PurchaseItem { ItemType = ItemType.Food, Subtype = "fine dining" },
new PurchaseItem { ItemType = ItemType.Food, Subtype = "liquor" }
},
Cost = 75.49
}
}
在这种情况下,我希望看到结果表明我在 Bytes-R-Us 的外围设备和糖果上花费了 75 美元,在 Bytes-R-Us 的游戏上花费了 100 美元,在 Foo Bar & 的食物和饮料上花费了 75.49 美元炙烤。像这样的:
var groupedTransactions = transactions.GroupBy(
x => new {PointOfSale = x.PointOfSale, Items = x.PurchaseItems},
y => y.Cost,
(x, y) => new Transaction
{
PointOfSale = x.PointOfSale,
PurchaseItems = x.Items,
Cost = y.Sum()
});
但是我怎样才能让x => new {PointOfSale = x.PointOfSale, Items = x.PurchaseItems} 像我描述的那样工作呢?
【问题讨论】:
-
使用 SelectMany。我不知道如何获得成本。尝试这样的事情: var groupedTransactions = transactions .SelectMany(x => x.PurchaseItems.Select(y => new { PointOfSale = x.PointOfSale, Type = y.Type, Subtype = y.Subtype })) .GroupBy(x => new { PointOfSale = x.PointOfSale, Items = x.Type, Subtype = x.Subtype }) .ToList();