【问题标题】:How to Flatten a dictionary of (int, dictionary)?如何展平(int,dictionary)的字典?
【发布时间】:2023-03-26 09:30:01
【问题描述】:

我有SortedDictionary<int, Dictionary<string, HashSet<long>>>

如何使用 Linq 展平结果?

我试过了:

var result = dictionary.Values.SelectMany(x => x);

但是我如何压平到最底部呢?

我需要收集int, string, HashSet<long>

【问题讨论】:

  • 您希望“扁平化”数据得到什么结果?
  • 你到底想得到什么? HashSet<long>的集合? long的集合?还有什么?

标签: c# linq dictionary


【解决方案1】:

你可以使用类似下面的东西:

var flattened = dictionary.SelectMany(x => x.Value.Select(y => (x.Key, y.Key, y.Value)));

这将产生一个 ValueTyple<int, string, HashSet<long>> 的 IEnumerable。

请注意,因为这里的类型是IEnumerable,它尚未具体化。您可能希望在末尾添加 .ToList()(在这种情况下,类型将为 List<ValueTyple<int, string, HashSet<long>>>)或将其转换为您想要的任何其他集合类型。

【讨论】:

  • 也许您想根据需要创建一个列表(集合)并避免使用varList<(int, string, HashSet<long>)>,那么它会是完美的+1
  • @Tim OP 没有指定他们想要一个列表。因此,可以将 IEnumerable 转换为任何集合类型。如果他们想要一个列表,他们可以简单地将 `.ToList() 附加到末尾。
  • 是的,但是IEnumerable ICollection,所以展示如何创建一个真实的集合并没有什么坏处,它有助于理解你的方法和结果来展示类型。集合实现IEnumerable<T>,但您的结果不是集合,而是延迟执行的 LINQ 查询。
  • @Tim 谢谢。我已经编辑了答案以添加该信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 2020-03-27
相关资源
最近更新 更多