[英]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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.