分组并连接元组列表 [英] Group and concatenate List of tuples
本文介绍了分组并连接元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个成对的列表(键,值),键和值都是字符串.我想用重复的键聚合元组.
I have a list of pairs (key, val) with both key and value being strings. I want to aggregate the tuples with duplicate keys.
For (key1, val1), (key2, val2), (key3, val3), (key1, val4), (key2, val5)
我要输出
(key1, val1+val4), (key2, val2+val5)
这是我当前的查询
var duplicates = Contents.Records.SelectMany(x => x.Users).Select(x => new { Name = x.Name, ID= x.ID}).GroupBy(x => x.ID).Select(x => new { x.Key, Names = x.Select(p=>p.Name).Aggregate((a,b) => a +","+b)}).ToArray();
但是在每个重复项的末尾,成员名称为空.
But at the end for each entry in duplicates the member Names is empty.
数据如下,每条记录都有一个列表用户.每个用户都有一个名称和一个ID. 我在做什么错了?
The data is as follows each Records has a List Users. Each user has a Name and an ID. What am I doing wrong?
推荐答案
Aggregate
看起来应该可以完成.但是我从不喜欢Aggregate
.语法不直观(在我看来).通常,其他方式看起来更清晰.拿这个:
Aggregate
looks like it should do the job. But I've never liked Aggregate
. The syntax is not intuitive (in my mind). Usually other ways look more lucid. Take this one:
Tuple<string,string>[] tuples = {
Tuple.Create("key1", "val1"),
Tuple.Create("key2", "val2"),
Tuple.Create("key3", "val3"),
Tuple.Create("key1", "val4"),
Tuple.Create("key2", "val5")
};
tuples.GroupBy(t => t.Item1, t => t.Item2)
.Select(g => Tuple.Create(g.Key, string.Join("+", g)))
.Dump(); // Linqpad output command
结果:
key1 val1+val4
key2 val2+val5
key3 val3
这篇关于分组并连接元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文