繁体   English   中英

划分清单 <string> 分成大小相等的子列表N

[英]Divide List<string> into sublists of equal size N

我正在尝试对字符串列表(大小为N)进行切片,并基于被切片成相等部分(X)的列表返回范围。

例如,如果我有一个由10个元素组成的列表,而我的层数为5。

元素0和1是第1层。元素2和3是第2层。在方法的最后,我返回在params中指定的层。

我正在努力的是,如果列表计数不能被层数整除。 例如,23/5 = 4.6。 因此,这将是5组4组,然后剩下3组。 我希望结果为5层,5层,5层,5层,5层,3层(最后一层只是剩余的元素数)。

到目前为止,我已经包含了我的代码,但是我真的在如何确保列表大小尽可能相等以及如何处理余数方面陷入困境。

// Gets a list and returns a range by the tier specified
public List<string> GetRangeByTierIndex(List<string> listToDivide, int numOfTiers, int tierIndexToGet)
{
    int numOfElementsPerList = listToDivide.Count / numOfTiers;

    int index = (tierToGet - 1) * numOfElementsPerList;

    return listToDivide.GetRange(index, numOfElementsPerList);
}

注意:忘了提及,我也不能使用LINQ(AOT和iOS问题)。

这个想法是使用模,这是listToDivide.Count除以numOfTiers余数。 如果该余数大于零,则索引小于或等于该余数的所有层将具有一个以上的元素。 因此,还必须更正每个层的起始索引。 请注意,我还没有编写任何检查(例如主列表中的元素数是否为零, numOfTiers < tierIndexToGet等),但是您可以根据需要添加这些检查)。 同样,对于您的示例,这将给出包含5、5、5、4、4 5, 5, 5, 4, 4元素的列表,而不是5、5、5、5、3 5, 5, 5, 4, 4元素5, 5, 5, 5, 3但我认为这更好。 无论如何,我希望它能满足您的需求。 代码应类似于:

public List<string> GetRangeByTierIndex(List<string> listToDivide, int numOfTiers, int tierIndexToGet)
{
    int remaining = listToDivide.Count % numOfTiers;
    int numOfElementsPerList = listToDivide.Count / numOfTiers;
    int index = (tierIndexToGet - 1) * numOfElementsPerList;
    if (remaining > 0)
    {
        // most increase position of index because of numOfElementsPerList correction bellow
        index += tierIndexToGet > remaining ? remaining : tierIndexToGet - 1;
        // first 'remaining-th' tiers will have +1 element
        numOfElementsPerList += tierIndexToGet <= remaining ? 1 : 0;
    }
    return listToDivide.GetRange(index, numOfElementsPerList);
}

示例:23和5。

  • 23/5 = 4 // 4层5-使用整数除法
  • 23%5 = 3 // 1层3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM