【问题标题】:Group and concatenate List of tuples组和连接元组列表
【发布时间】:2013-04-18 21:27:32
【问题描述】:

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

但在每个重复条目的末尾,成员名称为空。

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

【问题讨论】:

  • 我在您的分组和选择中没有看到明显的缺陷,并且确实可以针对一组样本数据运行它并获得我认为您想要的结果。您是否检查了输入以验证您期望的数据是否已加载?例如,拆分查询并在.SelectMany(...).Select(...) 之后执行ToList()。您的数据是否符合您的预期?

标签: c# linq ienumerable


【解决方案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

【讨论】:

    猜你喜欢
    • 2017-07-24
    • 1970-01-01
    • 2016-12-19
    • 2016-02-19
    • 2020-11-17
    • 2020-08-08
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多