首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将列表元素分组到字典

将列表元素分组到字典
EN

Stack Overflow用户
提问于 2013-05-17 16:30:14
回答 2查看 176关注 0票数 3

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

代码语言:javascript
复制
ConfigFile.ControllerList

此列表的类型为:

代码语言:javascript
复制
List<Controller>

如何将控制器从ControllerList添加到3个字典键。字典类似于:

代码语言:javascript
复制
Dictionary<int, List<Controller>> ControllerDictionary = new Dictionary<int, List<Controller>>();

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-17 16:37:01

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

代码语言:javascript
复制
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)对它们进行划分。然后将每个组转换为列表。

票数 4
EN

Stack Overflow用户

发布于 2013-05-17 16:37:50

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

代码语言:javascript
复制
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 empty开始,然后将y < 2更改为y < GROUP_SIZE,其中GROUP_SIZE是您想要的任意大小的组。甚至可以将其提取到扩展方法中:

代码语言:javascript
复制
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;
}

然后你可以这样做:

代码语言:javascript
复制
var groups = new[]
{
   "Item1",
   "Item2",
   "Item3",
   "Item4",
   "Item5",
   "Item6",
   "Item7",
   "Item8"
}.ToGroupedDictionary(3);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16604692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档