[英]Splitting String Array to Multiple Parts
我可以半@sss,但是我想要一種干凈的方式來完成它,而不會在以后產生任何麻煩。
private String[][] SplitInto10(string[] currTermPairs)
{
//what do i put in here to return 10 string arrays
//they are all elements of currTermPairs, just split into 10 arrays.
}
因此,我基本上想將一個字符串數組(currTermPairs)平均分為10或11個不同的字符串數組。 我需要確保沒有數據丟失並且所有元素都已成功傳輸
編輯:您將得到一個n大小的字符串數組。 需要發生的是該方法需要從給定的字符串數組中返回10個字符串數組/列表。 換句話說,將數組分成10個部分。
例如,如果我有
A B C D E F G H I J K L M N O P Q R S T U
我需要根據大小將其拆分為10個字符串數組或11個字符串數組,因此在這種情況下,我將擁有
A B
C D
E F
G H
I J
K L
M N
O P
Q R
S T
U <--Notice this is the 11th array and it is the remainder
如果您想習慣使用數組和for循環,這是不使用LINQ的解決方案:
// Determine the number of partitions.
int parts = currTermPairs.Length < 10 ? currTermPairs.Length : 10;
// Create the result array and determine the average length of the partitions.
var result = new string[parts][];
double avgLength = (double)currTermPairs.Length / parts;
double processedLength = 0.0;
int currentStart = 0;
for (int i = 0; i < parts; i++) {
processedLength += avgLength;
int currentEnd = (int)Math.Round(processedLength);
int partLength = currentEnd - currentStart;
result[i] = new string[partLength];
Array.Copy(currTermPairs, currentStart, result[i], 0, partLength);
currentStart = currentEnd;
}
return result;
項目總數可能無法被10整除。問題是如何分配不同長度的零件。 在這里,我嘗試將它們平均分配。 請注意強制轉換(double)currTermPairs.Length
。 為了獲得浮點除法而不是整數除法,這是必需的。
這是一些測試方法:
const int N = 35;
var arr = new string[N];
for (int i = 0; i < N; i++) {
arr[i] = i.ToString("00");
}
var result = new PatrtitioningArray().SplitInto10(arr);
for (int i = 0; i < result.Length; i++) {
Console.Write("{0}: ", i);
for (int k = 0; k < result[i].Length; k++) {
Console.Write("{0}, ", result[i][k]);
}
Console.WriteLine();
}
其輸出為(包含35個元素):
0: 00, 01, 02, 03,
1: 04, 05, 06,
2: 07, 08, 09,
3: 10, 11, 12, 13,
4: 14, 15, 16, 17,
5: 18, 19, 20,
6: 21, 22, 23,
7: 24, 25, 26, 27,
8: 28, 29, 30, 31,
9: 32, 33, 34,
我想說創建一個List<List<string>>
含有10或11(取數你真正想要的) List<string>
s,而做這樣的事情:
int i = 0;
int index;
foreach(string s in src)
{
index = i % lists.Length; //lists is the List<List<string>>
lists[index].Add(s);
i++;
}
當然,如果原始列表中至少有10或11個項目,則只能分為10或11個列表。
這將有助於按順序將它們按組排列(即{1、2},{3、4},{5、6},{7、8},{9、10},{11、12},{ 13,14},{15,16},{17,18},{19,20},{21}):
int groupSize = items.Length / 10;
string[][] sets = items.Select((str, idx) => new { index = idx, value = str })
.GroupBy(a => a.index / groupSize)
.Select(gr => gr.Select(n => n.value).ToArray())
.ToArray();
如果您有102個項目,這將為您提供10個數組(共10個項目)和一個數組(共2個項目)(其余)。 這是您所期望的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.