mihaifm / linq

linq.js - LINQ for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how to use select with chained groupby

lucas-pollus opened this issue · comments

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 linq in typescript but I couldn't. Can you help me?

Hi, you can do it like this:

// code
const custData = [
{ Name: 'Brian', PriceUnit: 10, Quantity: 1 },
{ Name: 'John', PriceUnit: 10, Quantity: 2 },
{ Name: 'Brian', PriceUnit: 10, Quantity: 3 }
];
var custList = from(custData)
.select(c => ({ Name: c.Name, Total: c.PriceUnit * c.Quantity }))
.groupBy(c => c.Name)
.select(g => ({ Name: g.key(), Total: g.sum(c => c.Total) }))
.toArray();
console.log(JSON.stringify(custList));

//output
// [{"Name":"Brian","Total":40},{"Name":"John","Total":20}]