我有一個C#字典Dictionary<MyKey, MyValue>
,我想根據MyKey.KeyType
將其拆分爲Dictionary<MyKey, MyValue>
的集合。 KeyType
是一個枚舉。有沒有辦法將C#通用字典拆分爲多個字典?
然後我將留下一個包含鍵值對的字典,其中MyKey.KeyType = 1
和另一個字典MyKey.KeyType = 2
等等。
有沒有這樣做的好方法,如使用Linq?
我有一個C#字典Dictionary<MyKey, MyValue>
,我想根據MyKey.KeyType
將其拆分爲Dictionary<MyKey, MyValue>
的集合。 KeyType
是一個枚舉。有沒有辦法將C#通用字典拆分爲多個字典?
然後我將留下一個包含鍵值對的字典,其中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
如果您想通過「關鍵字類型」到底鍵入詞典的詞典時,該方法是相似的:
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
我相信下面的工作?
dictionary
.GroupBy(pair => pair.Key.KeyType)
.Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value);
所以你實際上想要一個IDictionary<MyKey, IList<MyValue>>
類型的變量?
你可以只使用LINQ的的GroupBy功能:
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);
}
除非你只是希望有獨立的集合:
Dictionary myKeyTypeColl<KeyType, Dictionary<MyKey, KeyVal>>
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