我正在尝试在 LINQ 中执行复杂的 GroupBy,但我的键选择器遇到了问题。在下面的代码中,我可以按一个方向的键(按 SellerID、BuyerID)进行分组,但实际上我也需要按相反的键分组(按 SellerID、BuyerID 或 BuyerID、SellerID)。我这个查询的最终目标是,当键反转时,我需要将资产金额设为负数。这将允许我扣除双方存在的任何金额,然后我将只得到在该特定方面有金额的记录。
下面的代码应该解释它:
public class Record
{
public int RecordID;
public int SellerID;
public int BuyerID;
public List<Asset> Assets;
}
public class Asset
{
public int AssetID;
public decimal Amount;
}
var groups = new List<Record>
{
new Record { RecordID = 1, SellerID = 100, BuyerID = 200, Assets = new List<Asset> { new Asset { AssetID = 5, Amount = 10 }}},
new Record { RecordID = 2, SellerID = 100, BuyerID = 200, Assets = new List<Asset> { new Asset { AssetID = 5, Amount = 20 }}},
new Record { RecordID = 3, SellerID = 100, BuyerID = 200, Assets = new List<Asset> { new Asset { AssetID = 6, Amount = 60 }}},
new Record { RecordID = 4, SellerID = 200, BuyerID = 100, Assets = new List<Asset> { new Asset { AssetID = 5, Amount = 40 }}},
new Record { RecordID = 5, SellerID = 200, BuyerID = 100, Assets = new List<Asset> { new Asset { AssetID = 5, Amount = 50 }}},
new Record { RecordID = 6, SellerID = 200, BuyerID = 100, Assets = new List<Asset> { new Asset { AssetID = 6, Amount = 35 }}}
};
var result = groups.GroupBy(
r => new { r.SellerID, r.BuyerID },
r => r.Assets,
(r, assets) => new
{
r.SellerID,
r.BuyerID,
AssetSummation = assets.SelectMany(asset => asset).GroupBy(a => a.AssetID).Select(a2 => new { AssetID = a2.Key, Amount = a2.Sum(a3 => a3.Amount) })
});
我希望我的输出如下:
- 记录 1
- 卖家:100
- 买家:200
- 资产:
- 资产
- 资产 ID:6
- 数量:25
- 资产
- 记录 2
- 卖家:200
- 买家:100
- 资产:
- 资产 ID:5
- 数量:60
我想我有一个好的开始,但我不知道从这里去哪里。我如何翻转钥匙然后使金额为负数,以便我可以总结它们?我认为,在我能够做到这一点之后,我可以过滤掉任何值为 0 的资产行(这意味着记录是由逆向实现的。
编辑#1:也许我想做的是将groups变量加入到自身中,以求和加入两边的所有匹配记录。因此,我最终将左侧的 SellerID 连接到右侧的 BuyerID,将左侧的 BuyerID 连接到右侧的 SellerID。