I am trying to make complex GroupBy in LINQ, but I am having problems with my key selector. In the following code, I can group by my key in one direction (by SellerID, BuyerID), but I really need to group by my key and vice versa (by SellerID, BuyerID or BuyerID, SellerID). My ultimate goal of this query is that when the keys are reversed, I need to make the sum of the assets negative. This will allow me to exclude any amounts that exist on both sides, and then I get only records that have amounts on this particular side.
The following code should explain this:
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) }) });
I would like my conclusion to be as follows:
- Record 1
- Seller: 100
- Buyer: 200
- Assets:
- Record 2
- Seller: 200
- Buyer: 100
- Assets:
I think I have a good start, but I'm not sure where to go from here. How do I flip a key and then make the amounts negative so that I can sum them? I think that after I can do this, I can filter out any Asset lines where the value is 0 (this means that the recording was inverse.
EDIT # 1: Maybe what I'm trying to do is to attach a group variable to myself in SUM with all the relevant entries on both sides of the connection. Thus, I eventually join the Seller on the left side to BuyerID on the right side and BuyerID on the left side to the Seller on the right side.