【问题标题】:Is there a way of splitting a C# generic dictionary into multiple dictionaries?有没有办法将 C# 通用字典拆分为多个字典?
【发布时间】:2010-02-01 15:19:26
【问题描述】:
我有一个 C# 字典 Dictionary<MyKey, MyValue>,我想根据 MyKey.KeyType 将其拆分为 Dictionary<MyKey, MyValue> 的集合。 KeyType 是一个枚举。
然后我会留下一个包含键值对的字典,其中MyKey.KeyType = 1,另一个字典包含MyKey.KeyType = 2,依此类推。
有没有很好的方法,比如使用 Linq?
【问题讨论】:
标签:
c#
linq
dictionary
split
【解决方案1】:
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
【解决方案2】:
我相信以下方法会起作用?
dictionary
.GroupBy(pair => pair.Key.KeyType)
.Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value);
【解决方案3】:
所以你实际上想要一个IDictionary<MyKey, IList<MyValue>> 类型的变量?
【解决方案4】:
你可以只使用 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);
}
【解决方案5】:
除非您只想拥有单独的集合:
Dictionary myKeyTypeColl<KeyType, Dictionary<MyKey, KeyVal>>
【解决方案6】:
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