arogozine / LinqToTypeScript

LINQ to TypeScript
https://arogozine.github.io/linqtotypescript/
MIT License
139 stars 18 forks source link

how to use select with chained groupby #16

Closed lucas-pollus closed 3 years ago

lucas-pollus commented 3 years ago

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 3 years ago
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 3 years ago

@arogozine thanks!!!