C
C#4mo ago
cheeze2000

Aggregate data grouped by a key

I'm looking to aggregate these data:
// from this
[
new { id = 1, qty = 3 },
new { id = 2, qty = 5 },
new { id = 1, qty = 10 },
]

// to this
[
new { id = 1, qty = 13 },
new { id = 2, qty = 5 },
]
// from this
[
new { id = 1, qty = 3 },
new { id = 2, qty = 5 },
new { id = 1, qty = 10 },
]

// to this
[
new { id = 1, qty = 13 },
new { id = 2, qty = 5 },
]
my current approach iterates over the list into a dictionary and check for duplicate keys. i have a feeling it can be done in a cleaner way with System.Linq stuff
4 Replies
Angius
Angius4mo ago
.GroupBy() with .Select() and .Sum() could work
MODiX
MODiX4mo ago
Angius
REPL Result: Success
record Item(int Id, int Qty);

Item[] items = {
new(1, 3),
new(2, 5),
new(1, 10),
};

var newItems = items
.GroupBy(i => i.Id)
.Select(g => new Item(g.Key, g.Sum(i => i.Qty)));

newItems
record Item(int Id, int Qty);

Item[] items = {
new(1, 3),
new(2, 5),
new(1, 10),
};

var newItems = items
.GroupBy(i => i.Id)
.Select(g => new Item(g.Key, g.Sum(i => i.Qty)));

newItems
Result: List<Item>
[
{
"id": 1,
"qty": 13
},
{
"id": 2,
"qty": 5
}
]
[
{
"id": 1,
"qty": 13
},
{
"id": 2,
"qty": 5
}
]
Compile: 588.693ms | Execution: 99.162ms | React with ❌ to remove this embed.
Angius
Angius4mo ago
'Ere
cheeze2000
cheeze2000OP4mo ago
oh thanks
Want results from more Discord servers?
Add your server