简体   繁体   English

npm linq:分组多列

[英]npm linq: Grouping Multiple columns

I am trying to group by 2 columns in an array of objects and get a grouped sum total of a value.我正在尝试按对象数组中的 2 列分组,并获得一个值的分组总和。 i have been using linq for this and this is the code:我一直在使用 linq ,这是代码:

import Enumerate from "linq";

let data = [ 
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];

var result = Enumerate.from(data)
.groupBy((x) => x.Phase + ':'+ x.Task)
.select((x) => {
  return {
    Phase: x.first().Phase,
    Task: x.first().Task,
    Value: x.sum((y)=> y.Value | 0)
  };
})
.toArray();

console.log (result);

and I get the expected result:我得到了预期的结果:

Array(4)[
0: Object { Phase: "Phase 1" ,Task: "Task 1" ,Value: 20 }
1: Object { Phase: "Phase 1" ,Task: "Task 2" ,Value: 30 }
2: Object { Phase: "Phase 2" ,Task: "Task 1" ,Value: 60 }
3: Object { Phase: "Phase 2" ,Task: "Task 2" ,Value: 70 }
length: 4
]

I struggled a bit to come to this result and had to use some workarounds like a string key in the groupBy and x.first() when selecting the data.为了得到这个结果,我有点挣扎,并且在选择数据时不得不使用一些变通方法,例如 groupBy 和 x.first() 中的字符串键。 My question is, is this the proper way to do it?我的问题是,这是正确的方法吗? Or am I missing something?还是我错过了什么?

I'm not experienced with linq.js, but I'll give some insights based on my C# experience and what I can glean from the documentation.我对 linq.js 没有经验,但我会根据我的 C# 经验以及我从文档中收集到的内容提供一些见解。

It looks like there are additional arguments you can provide to the groupBy function to make this more elegant. 看起来您可以向groupBy function 提供额外的 arguments 以使其更加优雅。 The arguments are: arguments 是:

  1. the key selector键选择器
  2. the value selector值选择器
  3. a selector that merges the key and values into the desired output per group将键和值合并到每个组所需的 output 的选择器
  4. a compare selector to produce a comparable value from the key produced in #1比较选择器,用于从 #1 中生成的键生成可比较的值

So I think something like this should work:所以我认为这样的事情应该有效:

var result = Enumerate.from(data)
.groupBy((x) => ({Phase: x.Phase, Task: x.Task}),
         (x) => x.Value | 0,
         (key, values) => ({
             Phase: key.Phase,
             Task: key.Task,
             Value: values.sum()
         }),
         (key) => key.Phase + ':'+ key.Task)
)
.toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM