将列表元素分组到字典

我有一个包含8个元素的列表:

ConfigFile.ControllerList 

此列表的类型为:

 List 

如何将ControllerList中的控制器添加到3个字典键中。 字典就像:

 Dictionary<int, List> ControllerDictionary = new Dictionary<int, List>(); 

我想将前3个控制器添加到字典键0,然后想要将下3个控制器添加到字典键1,最后想要将最后2个控制器添加到字典键2.我怎么能这样做?

您可以使用/将列表拆分为子列表:

 var ControllerDictionary = ControllerList .Select((c, i) => new { Controller = c, Index = i }) .GroupBy(x => x.Index / maxGroupSize) .Select((g, i) => new { GroupIndex = i, Group = g }) .ToDictionary(x => x.GroupIndex, x => x.Group.Select(xx => xx.Controller).ToList()); 

我们的想法是首先按索引对元素进行分组,然后将它们除以int maxGroupSize(在您的情况下为3)。 然后将每个组转换为列表。

不确定是否有更优雅的解决方案,但这样的事情应该有效:

 var dict = new Dictionary>(); int x = 0; while (x < controllerList.Count) { var newList = new List { controllerList[x++] }; for (int y = 0; y < 2; y++) // execute twice if (x < controllerList.Count) newList.Add(controllerList[x++]); dict.Add(dict.Count, newList); } 

为了使其更通用,您还可以创建newList空,然后将y < 2更改为y < GROUP_SIZE ,其中GROUP_SIZE是您想要的任何大小的组。 甚至可以将其提取到扩展方法:

 public static Dictionary> ToGroupedDictionary (this IList pList, int pGroupSize) { var dict = new Dictionary>(); int x = 0; while (x < pList.Count) { var newList = new List(); for (int y = 0; y < pGroupSize && x < pList.Count; y++, x++) newList.Add(pList[x]); dict.Add(dict.Count, newList); } return dict; } 

然后你可以这样做:

 var groups = new[] { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8" }.ToGroupedDictionary(3);