分组并连接元组列表

时间:2013-04-18 21:27:33

标签: c# linq ienumerable

我有一个对(key,val)列表,其中键和值都是字符串。我想用重复键来聚合元组。

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();

但最后,对于每个重复条目,成员名称为空。

数据如下,每个记录都有一个List Users。每个用户都有一个名称和一个ID。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

Aggregate看起来应该做的工作。但我从未喜欢Aggregate。语法不直观(在我看来)。通常其他方式看起来更清晰。拿这个:

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