【问题标题】:Divide List<string> into sublists of equal size N将 List<string> 分成大小相等的子列表 N
【发布时间】:2014-11-13 13:23:15
【问题描述】:

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

例如,如果我有一个包含 10 个元素的列表,而我的层数是 5。

元素 0 和 1 是第 1 层。元素 2 和 3 是第 2 层。在方法结束时,我返回参数中指定的层。

我正在努力解决的问题是列表计数是否不能被层数整除。例如,23 / 5 = 4.6。所以这意味着它们将是 5 组 4 组,然后剩下 3 组。我希望结果是 5、5、5、5、3 的 5 层(最后一层只是剩余的元素数量)。

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

// 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 问题)。

【问题讨论】:

  • 对不起,我应该在我不能使用 LINQ 之前提到。
  • 我相信也有一些非 linq 解决方案
  • 您的第一个 10 元素和 5 层示例是 5 组 2,但在您的 23 元素和 5 层的第二个示例中,您说的是 4 组 5。不应该是 5 组4?
  • 是的,应该是 5 套 4 套 :)

标签: c# list


【解决方案1】:

这个想法是使用模数,它是listToDivide.Count 除以numOfTiers 的余数。如果该余数大于零,则索引小于或等于该余数的所有层将多一个元素。因此,也必须更正每一层的起始索引。请注意,我没有编写任何检查(例如,如果主列表中的元素数量为零,numOfTiers &lt; tierIndexToGet 等...但您可以根据需要添加这些检查)。此外,对于您的示例,这将提供带有 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);
}

【讨论】:

    【解决方案2】:

    示例:23 和 5。

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

    【讨论】:

    • 此解决方案的问题是,如果主列表中有 21 个元素,则层中的元素数将为 5,5,5,5,1。我的例子给出了 5, 4, 4, 4, 4,这是更好的分布
    猜你喜欢
    • 2022-10-29
    • 2019-01-14
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多