【问题标题】:Recommended way to convert IGrouping<TKey, TValue> to IDictionary<TKey, IEnumerable<TValue>>将 IGrouping<TKey, TValue> 转换为 IDictionary<TKey, IEnumerable<TValue>> 的推荐方法
【发布时间】:2013-11-23 01:34:18
【问题描述】:

这一定是重复的,但我的搜索没有产生我想要的结果。

看起来这应该相当简单,但似乎没有内置的 LINQ 机制来实现这一点。一些帮助将不胜感激。

...也有可能我做错了。我有一组具有属性Foo 的可枚举对象,我想创建一个字典,其中Foo 属性是字典的键,其中值是具有Foo 的对象的枚举作为相同的值。

【问题讨论】:

  • 你的意思是IEnumerable&lt;IGrouping&lt;TKey, TValue&gt;&gt;
  • 也许我会。 IGrouping 不是我很熟悉的东西。

标签: c# linq ienumerable grouping


【解决方案1】:

这应该可行:

var dict = yourGroup.ToDictionary(g=>g.Key, g=>g.Select(x=>x));

或使用AsEnumerable 生成值:

var dict = yourGroup.ToDictionary(g=>g.Key, g=>g.AsEnumerable());

【讨论】:

  • 知道它必须是简单的东西。谢谢
  • 这是您所能得到的最接近的结果,但仍然不完全正确——IEqualityComparer 可能不同。
  • @CoryNelson IEqualityComparer 不是 data 的一部分,我们可以随时为字典指定 IEqualityComparer 为我们想要的任何内容。我也不知道如何从群里提取 IEqualityComparer,如果你知道,请随时分享,我将不胜感激。
  • 我觉得这没什么大不了的。第一,我们可以提供IEqualityComparer in ToDictionary,第二,我们应该知道我们的数据。
猜你喜欢
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2014-02-19
  • 2016-06-14
  • 2011-01-16
  • 1970-01-01
  • 2016-11-20
相关资源
最近更新 更多