【问题标题】:Merge two collections in Linq [duplicate]在Linq中合并两个集合[重复]
【发布时间】:2018-12-11 14:44:24
【问题描述】:

我有IEnumerable<GroupResult<T>>,其中GroupResult<T> 如下:

public class GroupResult<T>
{
 public string Key { get; set; }
 public IEnumerable<T> Items { get; set; }
}

假设集合如下所示:

{
Key: "1",
Items: { "A", "B" }
}

{
Key: "1",
Items: { "C", "D" }
}

{
Key: "2",
Items: { "E", "F" }
}

我可以执行什么操作来获得以下信息:

{
Key: "1",
Items: { "A", "B", "C", "D" }
}

{
Key: "2",
Items: { "E", "F" }
}

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您可以使用Dictionary&lt;string,IEnumerable&lt;T&gt;&gt;,而不是使用IEnumerable&lt;GroupResult&lt;T&gt;&gt;,这样可以首先防止重复键。

标签: c# linq ienumerable


【解决方案1】:

使用GroupBy()

var result = intput.GroupBy(x => x.Key)
                   .Select(x => new GroupResult() 
                          { 
                              Key = x.Key, 
                              Items = x.SelectMany(y => y.Items) 
                           });

https://dotnetfiddle.net/p8HklJ

【讨论】:

  • 不幸的是,这并没有改变任何东西:imgur.com/a/l9PS7EG - 在调试器中看到的 ToString 定义为:键 {Count}。每个 GroupResult 有 1 个项目,即使是具有相同 Key 的项目。
猜你喜欢
  • 2012-04-19
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多