我有一个包含8个元素的列表:
ConfigFile.ControllerList此列表的类型为:
List<Controller>如何将控制器从ControllerList添加到3个字典键。字典类似于:
Dictionary<int, List<Controller>> ControllerDictionary = new Dictionary<int, List<Controller>>();我想将前3个控制器添加到字典键0,然后将下3个控制器添加到字典键1,最后将最后2个控制器添加到字典键2。我该怎么做?
发布于 2013-05-17 16:37:01
您可以使用/将列表拆分为子列表:
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)对它们进行划分。然后将每个组转换为列表。
发布于 2013-05-17 16:37:50
不确定是否有更优雅的解决方案,但这样的解决方案应该是可行的:
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是您想要的任意大小的组。甚至可以将其提取到扩展方法中:
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);https://stackoverflow.com/questions/16604692
复制相似问题