按可除数将一个列表分成多个列表

Sim*_*ice 0 c#

我正在研究一种动态解决方案,其中我需要根据传入的变量将一个大列表分成x个列表。

因为我正在使用的类非常复杂,所以为了获得最小的可复制问题,我选择了下面的代码来代表我的问题100%。

我面临的问题是下面的代码被0除的问题。

当我改变面对其他问题if (j % i == 0),以if (j % 3 == 0)我得到的结果"1", "4", "7"

当我看着从if列表中的列表中删除一项时,上面的变化我得到了

3个新列表,原始列表中剩余3个项目。

1 5 5

2 7

3

4 6 8

void Main()
{
var listsToSplit = 3;

var l = new List<string>(){
    "1", "2", "3", "4", "5", "6", "7", "8",
    "9"
};

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

for (var i = 0; i < listsToSplit; i++)
{
    for (var j = 0; j < l.Count; j++)
    {
        if (j % i == 0)
        {
            List<string> value;

            if (dict.TryGetValue(i, out value))
            {
                value.Add(l[j]);
            }
            else
            {
                var newListItem = new List<string> {l[j]};
                dict.Add(i, newListItem);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

}

理想情况下,我要从中列出3个清单

1, 4, 7

2, 5, 8

3, 6, 9
Run Code Online (Sandbox Code Playgroud)

然后说出我有10和11后,我就需要清除所有剩余的物品。

我看过

将List <string>拆分为多个列表

使用LINQ将列表拆分为子列表

这些都接近我的需求,但是它们并不是我所需要的完整解决方案,因此,我认为这不是我的问题的重复,并且希望获得所有可能的帮助。

谢谢

西蒙

Dmi*_*nko 6

如果我理解正确,则希望将初始列表3按项索引模数分组3

  1. 第一组-第0、3d,6,...第3N个项目...
  2. 第二组-第1,第4,第7,... 3N +第一项...
  3. 3d组-第2个第5、8,... 3N个+第2个项目...

您可以尝试在Linq的帮助下它们分组

  List<List<string>> result = l
    .Select((value, index) => new {
      value,
      index
    })
   .GroupBy(item => item.index % listsToSplit, item => item.value)
   .Select(chunk => chunk.ToList())
   .ToList();
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要一本字典:

  var dict = l
    .Select((value, index) => new {
      value,
      index
    })
    .GroupBy(item => item.index % listsToSplit, item => item.value)
    .ToDictionary(chunk => chunk.Key, chunk => chunk.ToList());
Run Code Online (Sandbox Code Playgroud)