我有一个“主”列表(字符串),其中包含几百个字符串,需要将它们分成n个较小的列表(字符串),每个较小的列表具有相同的长度,然后传递给一个对象的构造函数,该对象将添加到自己的列表中。为此,我的代码如下所示:
Private Function GetListOfClassA() as List(Of ClassA)
Dim listToReturn As New List(Of ClassA)
Dim sublistLength As Integer = 38
Dim masterList as List(Of String) = StaticClass.GetCombinedClassAInfo()
For index As Integer = 0 To (masterList.Count / sublistLength) - 1 'This will always divide evenly
Dim startIndex As Integer = index * sublistLength 'I know there's a bit of miscalculation here but at this point I think it's beside point
Dim endIndex As Integer = startIndex + sublistLength
Dim tempList as List(Of String) = masterList.GetRange(startIndex, endIndex)
Dim tempClassA As New ClassA(tempList)
listToReturn.Add(tempClassA)
Next
Return listToReturn
End Function
我期望的行为是tempList
在循环的每次迭代中都是全新的,因此创建的每个tempList
的长度为38
。但是,当我运行此代码时,tempList
是38
,然后是76
,依此类推。第二次迭代的值被添加到上一次迭代的tempList
中,然后用于实例化tempClassA
,我不知道为什么。
我仔细检查了startIndex
和endIndex
的计算是否正确,是否正确。在第二次迭代中,startIndex = 38
和endIndex = 76
任何见解都会受到赞赏。
答案 0 :(得分:2)
EndIndex错误,因为参数要求输入“ count”,而不是结束索引:
公共System.Collections.Generic.List GetRange(整数索引,整数计数);
像这样尝试:
Dim tempList as List(Of String) = masterList.GetRange(startIndex, sublistLength)
答案 1 :(得分:0)
也许您可以尝试这样的事情
Dim tempList = New List(Of String) From masterList.GetRange(startIndex, endIndex)