Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to use select with chained groupby #89

Open
lucas-pollus opened this issue Oct 20, 2021 · 1 comment
Open

how to use select with chained groupby #89

lucas-pollus opened this issue Oct 20, 2021 · 1 comment

Comments

@lucas-pollus
Copy link

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?

@tiandongmao
Copy link

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}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants