Reputation: 652
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?
Upvotes: 1
Views: 5622
Reputation: 109165
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
Upvotes: 1