-2

我的字典对象中有以下数据。

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# 编码来实现。

4

2 回答 2

4

假设输入不是字典(没有意义)而是 a 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());

如果您还想订购组件,您必须OrderByToList.

于 2013-04-16T11:36:32.710 回答
1
List<KeyValuePair<String, Component>> dataNotGrouped;
var grouped = dataNotGrouped.GroupBy(e=>e.Key);

完毕。

然后您可以将其转换为Dictionary<String, List<Component>>或转换为List<KeyValuePair<String, Component>>您想要的任何东西!您的列表正在按 Key 分组!

于 2013-04-16T11:38:00.983 回答