小组和串联列表[英] Group and concatenate List of tuples

本文是小编为大家收集整理的关于小组和串联列表的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个对(钥匙,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();

但最终重复的每个条目的成员名称为空.

数据如下所示,每个记录都有列表用户.每个用户都有一个名称和ID. 我在做什么错?

推荐答案

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

本文地址:https://www.itbaoku.cn/post/1557109.html

问题描述

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?

推荐答案

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