how to use select with chained groupby
lucas-pollus opened this issue · 2 comments
lucas-pollus commented
Hello,
In c# I have the following code:
// customers
// Name: Brian, PriceUnit: 10, Quantity: 1
// Name: John, PriceUnit: 10, Quantity: 2
// Name: Brian, PriceUnit: 10, Quantity: 3
var list = customers
.Select(c => new { c.Name, Total = c.PriceUnit * c.Quantity })
.GroupBy(g => new { g.Name })
.Select(x => new { x.Name, Total = x.Sum(s => x.Total)})
.ToList();
// list
// Name: Brian, Total: 40
// Name: John, Total: 20
I tried to reproduce this using LinqToTypeScript but I couldn't. Can you help me?
arogozine commented
import { from } from "linq-to-typescript"
interface ICustomer {
name: string
priceUnit: number
quantity: number
}
const customers: ICustomer[] = [
{ name: "Brian", priceUnit: 10, quantity: 1 },
{ name: "John", priceUnit: 10, quantity: 2 },
{ name: "Brian", priceUnit: 10, quantity: 3 }
]
const list = from(customers)
.select(c => {
return { name: c.name, total: c.priceUnit * c.quantity }
})
.groupBy(({name}) => name)
.select(group => {
const total = group.sum(s => s.total)
return { name: group.key, total }
})
.toArray()
for (const { name, total } of list) {
console.log(`Name: ${name}, Total: ${total}`)
}
lucas-pollus commented
@arogozine thanks!!!