c# - 从旧字典填充新字典

标签 c# dictionary

我有一个Dictionary<string, int>其中字符串是随机的字符集合,int 是该字符串的 ASCII 总和。

例如

    ["aaaaaaaaab", 971],
    ["aaaaaaaaba", 971],
    ["aaaaaaabaa", 971],
    ["aaaaaabaaa", 971]

我想根据原始字典创建一个新字典,其中新键是原始字典中的值,新值是 List<string>其中包含所有以 ASCII 和作为键的字符串。

例如

    [971, List<string>{ "aaaaaaaaab", "aaaaaaaaba", "aaaaaaabaa", "aaaaaabaaa"}]

我怎样才能实现这个目标?我无法理解所需的步骤。

最佳答案

使用可以 GroupBy ToDictionary

前提是:

  1. 按旧的 Value 分组
  2. 给定 GroupBy 的值
  3. 项目到新的字典
    • 这将是 KeyValuePair分组列表从原始字典来看,依次有 key从中选择 ( .Select(y => y.Key )

示例

var newDict = old.GroupBy(x => x.Value)
                 .ToDictionary(x => x.Key, x => x.Select(y => y.Key)
                                                 .ToList());

其他资源

Enumerable.GroupBy Method

Groups the elements of a sequence.

Enumerable.ToDictionary Method

Creates a Dictionary<TKey,TValue> from an IEnumerable<T>.

关于c# - 从旧字典填充新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031854/

相关文章:

c# - 在 C# 中实现 SSL 隧道

用于对 ls -l 输出中的值求和的 Python 脚本

具有返回迭代器的查找功能的 Python 字典

python - 在用户输入中搜索关键字,并在字典中找到对应的关键字

c# - 使用部分类而不是抽象类有什么好处?

c# - 我如何将目录中的文件名读取到数组中

c# - 可以相信 Page_Unload 将始终运行并且是放置 Dispose() 代码的好地方吗?

c# - 如何从员工的 UserPrincipal 对象获取经理的 UserPrincipal 对象

python - 如何从 python 中的嵌套字典中获取特定键及其值?

excel - 使用后期绑定(bind)但不使用早期绑定(bind)时,字典出现运行时错误