有没有一种方法将C#泛型字典拆分成多个字典?

5
我有一个C#字典Dictionary<MyKey, MyValue>,我想将其拆分为一组Dictionary<MyKey, MyValue>,基于MyKey.KeyTypeKeyType是一个枚举类型。
然后,我将得到一个包含键值对的字典,其中MyKey.KeyType = 1,另一个字典中MyKey.KeyType = 2,以此类推。
是否有一种不错的方法来做到这一点,例如使用Linq?
6个回答

10
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

1

我相信以下的代码会有效吗?

dictionary
    .GroupBy(pair => pair.Key.KeyType)
    .Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value);

0
你可以使用GroupBy Linq函数:
            var dict = new Dictionary<Key, string>
                   {
                       { new Key { KeyType = KeyTypes.KeyTypeA }, "keytype A" },
                       { new Key { KeyType = KeyTypes.KeyTypeB }, "keytype B" },
                       { new Key { KeyType = KeyTypes.KeyTypeC }, "keytype C" }
                   };

        var groupedDict = dict.GroupBy(kvp => kvp.Key.KeyType);

        foreach(var item in groupedDict)
        {
            Console.WriteLine("Grouping for: {0}", item.Key);
            foreach(var d in item)
                Console.WriteLine(d.Value);
        }

0

除非你只想要单独的集合:

Dictionary myKeyTypeColl<KeyType, Dictionary<MyKey, KeyVal>>

0

所以你实际上想要一个类型为IDictionary<MyKey, IList<MyValue>>的变量吗?


-1
Dictionary <int,string> sports;
sports=new Dictionary<int,string>();
sports.add(0,"Cricket");
sports.add(1,"Hockey");
sports.add(2,"Badminton");
sports.add(3,"Tennis");
sports.add(4,"Chess");
sports.add(5,"Football");
foreach(var spr in sports)
console.WriteLine("Keu {0} and value {1}",spr.key,spr.value);

输出:

Key 0 and value Cricket
Key 1 and value Hockey
Key 2 and value Badminton
Key 3 and value Tennis
Key 4 and value Chess
Key 5 and value Football

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接