将列表元素分组到字典

时间:2013-05-17 08:30:14

标签: c# list dictionary

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

ConfigFile.ControllerList

此列表的类型为:

List<Controller>

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

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

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

2 个答案:

答案 0 :(得分:4)

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

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)。然后将每个组转换为列表。

答案 1 :(得分:1)

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

var dict = new Dictionary<int, List<Controller>>();

int x = 0;
while (x < controllerList.Count)
{
   var newList = new List<Controller> { 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<int, List<T>> ToGroupedDictionary<T>
   (this IList<T> pList, int pGroupSize)
{
   var dict = new Dictionary<int, List<T>>();

   int x = 0;
   while (x < pList.Count)
   {
      var newList = new List<T>();

      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);
相关问题