我如何做一个LINQ GroupBy的关键可以逆转

本文关键字:逆转 GroupBy 何做一 LINQ | 更新日期: 2023-09-27 18:04:27

我正试图在LINQ中做一个复杂的GroupBy,但我的键选择器有问题。在下面的代码中,我能够在一个方向上按键分组(通过SellerID、BuyerID),但实际上我也需要在反向方向上按键分组(通过SellerID、BuyerID或BuyerID、SellerID)。这个查询的最终目标是,当键颠倒时,我需要使Asset金额为负。这将允许我扣除两边存在的任何金额,然后我最终将只得到在特定一侧有金额的记录。

下面的代码应该解释它:

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
    • 资产:
      • 资产
        • AssetID: 6
        • 数量:25
  • 记录2
    • 卖家:200
    • 买家:100
    • 资产:
      • AssetID: 5
      • 数量:60

我认为我有一个良好的开端,但我不确定从这里去哪里。我如何翻转钥匙,然后使金额为负,这样我就可以把它们加起来?我认为,在我能够做到这一点之后,我可以过滤掉任何值为0的资产行(这意味着记录是由逆完成的)。

编辑#1:也许我要做的是将groups变量连接到自身,以SUM连接两侧的所有匹配记录。所以我最终会把左边的SellerID和右边的BuyerID连接起来左边的BuyerID和右边的SellerID连接起来。

我如何做一个LINQ GroupBy的关键可以逆转

下面是返回预期结果的查询:

var result = records
    .SelectMany(r => new[] { r, new Record { // 1
           SellerID = r.BuyerID, 
           BuyerID = r.SellerID, 
           Assets = r.Assets.Select(a => new Asset { 
                        AssetID = a.AssetID, 
                        Amount = -a.Amount
                    }).ToList() }})
    .GroupBy(r => new { r.SellerID, r.BuyerID }) // 2
    .Select(g => new { // 3
           Seller = g.Key.SellerID,
           Buyer = g.Key.BuyerID,
           Assets = g.SelectMany(r => r.Assets)
                     .GroupBy(a => a.AssetID)
                     .Select(ag => new { 
                         AssetID = ag.Key,
                         Amount = ag.Sum(a => a.Amount) })
                     .Where(x => x.Amount > 0) });

它是如何工作的?非常简单:

  1. 对于每个记录,我选择两个记录-一个是原样的,另一个是反向的卖方和买方(所有资产都有负金额)。然后我用SelectMany平掉所有记录。
  2. 按卖方和买方分组。
  3. Rest是对每组资产金额的简单计算。

BTW代替返回匿名对象,你可以在最后的选择语句中创建你的RecordAsset对象

辅助类:

public class RecordItem
{
    public int SellerID;
    public int BuyerID;
    public int AssetID;
    public decimal Amount;
}
平等比较器:

public class RecordItemEqualityComparer : IEqualityComparer<RecordItem>
{
    public bool Equals(RecordItem x, RecordItem y)
    {
        if (x.AssetID != y.AssetID)
            return false;
        if (x.BuyerID == y.BuyerID && x.SellerID == y.SellerID)
            return true;
        if (x.BuyerID == y.SellerID && x.SellerID == y.BuyerID)
            return true;
        return false;
    }
    public int GetHashCode(RecordItem obj)
    {
        return string.Format("{0}_{1}", obj.BuyerID * obj.SellerID, obj.AssetID).GetHashCode();
    }
}

And LINQ query:

var recordItemComparer = new RecordItemEqualityComparer();
var items = groups.SelectMany(r => r.Assets.Select(a => new RecordItem {
                                                            BuyerID = r.BuyerID,
                                                            SellerID = r.SellerID,
                                                            AssetID =a.AssetID,
                                                            Amount = a.Amount
                                                        }))
                  .GroupBy(ri => ri, recordItemComparer)
                  .Select(g => new RecordItem() {
                        BuyerID = g.Key.BuyerID,
                        SellerID = g.Key.SellerID,
                        AssetID = g.Key.AssetID,
                        Amount = g.Sum(ri => (ri.BuyerID == g.Key.BuyerID) ? ri.Amount : -1 * ri.Amount)
                  }).ToList();

返回你想要的:一个包含2项的列表。Sum计算正确,但买方卖方顺序可能不正确,因此Sum可能是-60而不是60

p。这真的是一个很好的挑战!