我想按键对键值对列表进行分组,然后对具有相同值列表的所有键进行分组。
这是一个例子
| Key | Value |
|:----|------:|
| 1 | A |
| 1 | B |
| 1 | C |
| 2 | A |
| 2 | B |
| 3 | A |
这是我想要的结果
| Keys | Values |
|:-----|-------:|
| 1,2 | A,B |
| 1 | C |
| 3 | A |
我从经典的GroupBy
开始,但是在第二步中我将键分组
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("1", "A"),
new KeyValuePair<string, string>("1", "B"),
new KeyValuePair<string, string>("1", "C"),
new KeyValuePair<string, string>("2", "A"),
new KeyValuePair<string, string>("2", "B"),
new KeyValuePair<string, string>("3", "A")
};
var groupingFirstStep = pairs.GroupBy(p => p.Key);
| Key | Values |
|:-----|-------:|
| 1 | A,B,C |
| 2 | A,B |
| 3 | A |
其他示例:左侧为输入,右侧为预期结果
| Key | Value | | Keys | Values |
|:----|------:| |:-----|-------:|
| 1 | A | | 1,2 | A,B |
| 1 | B |
| 2 | A |
| 2 | B |
| Key | Value | | Keys | Values |
|:----|------:| |:-----|-------:|
| 1 | A | | 1,2 | A,B |
| 1 | B | | 1 | C |
| 1 | C |
| 2 | A |
| 2 | B |
| Key | Value | | Keys | Values |
|:----|------:| |:-----|-------:|
| 1 | A | | 1,2 | A,B |
| 1 | B | | 1,3 | C |
| 1 | C | | 3 | A |
| 2 | A |
| 2 | B | Other possibility
| 3 | A | | 1,3 | A,C |
| 3 | C | | 1,2 | B |
| 2 | A |
答案 0 :(得分:1)
我认为这就是您所需要的。我用C省略了const sql = require('mssql')
var config = {
user: 'user',
password: 'pw',
server: 'AzureServerAddress',
database: 'DB',
options: {
encrypt: true // if on Windows Azure
},
parseJSON: false,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 60000
}
}
function updateSQL(input) {
return new Promise(function (resolve, reject) {
var results = []
sql.connect(config, err => {
// ... error checks
const request = new sql.Request()
let data = []
request.input('t1', sql.Int, input.Folder_ID)
request.input('t2', sql.Int, input.PR_ID)
request.stream = true
request.query('update table1 set t1= @t1 where t2= @t2')
request.on('done', result => {
sql.close()
console.log(result.rowsAffected)
resolve(results)
})
})
}).catch(error => log.i(`${fn} error ${error}`));
}
,因为我假设您想知道在值(在这种情况下为KeyValuePair
)相同的情况下如何对键进行分组:
A,B
答案 1 :(得分:0)
您可以使用.GroupBy
中的this overload来投影值。
类似这样的东西:
static void Main(string[] args)
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("1", "A"),
new KeyValuePair<string, string>("1", "B"),
new KeyValuePair<string, string>("1", "C"),
new KeyValuePair<string, string>("2", "A"),
new KeyValuePair<string, string>("2", "B"),
new KeyValuePair<string, string>("3", "A")
};
IEnumerable<string> groupings = pairs.GroupBy(x => x.Key, x => x.Value, (x, y) => $"{x}\t|\t{string.Join(",", y)}");
foreach (string groupItem in groupings)
{
Console.WriteLine(groupItem);
}
}
输出:
1 | A,B,C
2 | A,B
3 | A