我的词典对象中有以下数据。
List<KeyValuePair<String, Component>> lstCountry = new List<KeyValuePair<string, Component>>();
//Sample data in above dictionary object
ASIA, Component object(India)
ASIA, Component object(China)
ASIA, Component object(Sri Lanka)
ASIA, Component object(Bangladesh)
..
..
..
EUROPE, Component object(United Kingdom)
EUROPE, Component object(Germany)
EUROPE, Component object(France)
..
..
现在我想将这些值添加到另一个主国家字典中,该字典将包含以下示例数据:
Dictionary<String, List<Component>> dicCountries = new Dictionary<string, List<Component>>();
//ASIA, List<Component> Object of all the ASIA countries
//AFRICA, List<Component> Object of all the AFRICA countries
//EUROPE, List<Component> Object of all the EUROPE countries
...
...
请使用LINQ建议是否可行,或者我们可以通过简单的C#编码实现。
答案 0 :(得分:4)
假设输入不是字典(没有意义),而是List<KeyValuePair<String, Component>>
,这可行:
Dictionary<String, List<Component>> dicCountries = lstCountry
.GroupBy(kv => kv.Key)
.OrderBy(g => g.Key) // added OrderBy because of your title although it's not clear
.ToDictionary(g => g.Key, g => g.Select(kv => kv.Value).ToList());
如果您还想订购组件,则必须在OrderBy
之前添加ToList
。
答案 1 :(得分:1)
List<KeyValuePair<String, Component>> dataNotGrouped;
var grouped = dataNotGrouped.GroupBy(e=>e.Key);
完成。
然后你可以将它转换为Dictionary<String, List<Component>>
或List<KeyValuePair<String, Component>>
或whateva你想要的!您的列表按密钥分组!