我正在尝试在LINQ中进行一项复杂的GroupBy操作,但是我在键选择器方面遇到了问题。在下面的代码中,我能够按照一个方向(按SellerID,BuyerID)分组,但实际上我还需要按照相反的方式(按SellerID,BuyerID或BuyerID,SellerID)分组我的关键字。我的最终目标是,当键被颠倒时,我需要使资产金额变为负数。这将允许我计算出两边存在的任何金额的净额,然后我最终将得到只有在特定方面具有金额的记录。
以下代码应该可以解释:
我希望输出的结果如下:
编辑#1:也许我试图做的是将组变量与自身连接,以对连接两侧的所有匹配记录进行求和。因此,我将在左侧将卖方ID与右侧的买方ID连接,在左侧将买方ID与右侧的卖方ID连接。
以下代码应该可以解释:
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
编辑#1:也许我试图做的是将组变量与自身连接,以对连接两侧的所有匹配记录进行求和。因此,我将在左侧将卖方ID与右侧的买方ID连接,在左侧将买方ID与右侧的卖方ID连接。