c# - 有没有办法将 C# 泛型字典拆分成多个字典?

标签 c# linq dictionary split

我有一个 C# 字典 Dictionary<MyKey, MyValue>我想把它分成 Dictionary<MyKey, MyValue> 的集合, 基于 MyKey.KeyType . KeyType是一个枚举。

然后我会得到一个包含键值对的字典,其中 MyKey.KeyType = 1 , 和另一本词典,其中 MyKey.KeyType = 2 , 等等。

有没有好的方法,比如使用 Linq?

最佳答案

var dictionaryList = 
    myDic.GroupBy(pair => pair.Key.KeyType)
         .OrderBy(gr => gr.Key)  // sorts the resulting list by "KeyType"
         .Select(gr => gr.ToDictionary(item => item.Key, item => item.Value))
         .ToList(); // Get a list of dictionaries out of that

如果你想要一个最终由“KeyType”键控的字典的字典,方法是类似的:

var dictionaryOfDictionaries = 
    myDic.GroupBy(pair => pair.Key.KeyType)
         .ToDictionary(gr => gr.Key,         // key of the outer dictionary
             gr => gr.ToDictionary(item => item.Key,  // key of inner dictionary
                                   item => item.Value)); // value

关于c# - 有没有办法将 C# 泛型字典拆分成多个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2177667/

相关文章:

c# - nHibernate 中 Restrictions.Eq 的命名空间

c# - Autofac:使用非泛型接口(interface)注册泛型类型

c# - 排序列表并在排序后将特定元素保留在列表末尾

c# - 我怎样才能从一个非类型化的表达式返回到一个类型化的表达式?

javascript - JS : Not been able to add the assertive arrays(dictionary) into their specific parent value

C# - 以编程方式打开和关闭 excel 文件的正确方法

c# - 将字符串作为文件返回时输出\n 作为换行符

python - 如何从字符串中提取多次出现的 dict?

sql - 如何将此 SQL 查询转换为 LINQ 或 Lambda 表达式?

c++ - C++14 中 vector 的 unordered_map 和 erase-remove 习语的奇怪行为