将列表元素分组到字典 [英] Grouping list elements to dictionary
问题描述
我有一个包含8个元素的列表:
I have a list that contains 8 elements:
ConfigFile.ControllerList
此列表是以下类型:
List<Controller>
如何将Controllers从ControllerList添加到3个字典键。字典如下:
How can i add Controllers from ControllerList to 3 dictionary keys. Dictionary is like:
Dictionary<int, List<Controller>> ControllerDictionary = new Dictionary<int, List<Controller>>();
我要添加前3个控制器到字典键0,然后要添加下一个3个控制器到字典键1,最后要添加最后2个控制器到字典键2.我该怎么做?
I want to add first 3 controllers to dictionary key 0, then want to add next 3 controllers to dictionary key 1 and lastly want to add last 2 controllers to dictionary key 2. How can i do that?
推荐答案
code> / 将列表分成子列表:
You can use /
to split the list into sub-list:
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)。然后将每个组转换为列表。
The idea is to first group the elements by indexes, then divide them by an int
maxGroupSize(in your case 3). Then convert each group to a list.
这篇关于将列表元素分组到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!