Group and concatenate List of tuples

ぃ、小莉子 提交于 2019-12-13 20:05:40

问题


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) 

I want output

(key1, val1+val4), (key2, val2+val5)

This is my current query

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.

The data is as follows each Records has a List Users. Each user has a Name and an ID. What am I doing wrong?


回答1:


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

result:

key1    val1+val4
key2    val2+val5
key3    val3


来源:https://stackoverflow.com/questions/16093395/group-and-concatenate-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!