我需要将一个数字分成偶数部分,例如:
32427237需要成为324 272 37
103092501需要成为103 092 501
我相信我可以接下来的数字,但我确信有一种更有效的方式,因为我不想错过这些数字中的字符 - 数字本身可以是任意长度所以如果数字是1234567890我希望它分成这些部分123 456 789 0
我已经看过其他语言的例子,比如Python等,但我不太了解它们将它们转换为C# - 循环通过字符然后在第三个获取前一个然后该索引来获取字符串的部分可能做好这份工作,但我愿意接受如何更好地完成这项工作的建议.
我想把IEnumerable<T>它分成固定大小的块.
我有这个,但由于所有列表创建/复制,它似乎不优雅:
private static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> items, int partitionSize)
{
List<T> partition = new List<T>(partitionSize);
foreach (T item in items)
{
partition.Add(item);
if (partition.Count == partitionSize)
{
yield return partition;
partition = new List<T>(partitionSize);
}
}
// Cope with items.Count % partitionSize != 0
if (partition.Count > 0) yield return partition;
}
Run Code Online (Sandbox Code Playgroud)
有没有更惯用的东西?
编辑:虽然这已被标记为Divide数组的副本到子序列数组的数组,但它不是 - 该问题涉及拆分数组,而这是关于IEnumerable<T>.此外,该问题要求填充最后一个子序列.这两个问题密切相关,但并不相同.
我使用的方法处理时间较长,需要返回许多结果,但正确的结果可能是返回的任何结果,比如说在 300,000 个结果之后,但其余 700,000 个结果是否正确将在下面检查主要代码:
//a that suppose to return a value at need.
//Main func might need few returns and not all so
static IEnumerable<int> foo() {
//long recusive process, might contain over 1 million results if being asked to yield all.
yield return ret;
}
static void Main(string[] args) {
var a = foo();
while (true) {
var p = a.Take(300); //takes first 300 every loop in the while-loop
foreach (var c in p) {
//does something with …Run Code Online (Sandbox Code Playgroud) 我有一维一维的数组:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
Run Code Online (Sandbox Code Playgroud)
我想将这个1D数组划分为4行5列的2D数组,其中前5个值进入第1行,后5个进入第2行,依此类推.最终结果应如下所示:
array2D:
[[10, 11, 12, 13, 14]
[20, 21, 22, 23, 24]
[30, 31, 32, 33, 34]
[40, 41, 42, 43, 44]]
Run Code Online (Sandbox Code Playgroud)
实际上,阵列将更长(可能超过100行),但列数为5,行数可以分为5.我已经简化了例如.这是我到目前为止所尝试的:
int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
int[,] array2D = new int[(array.Length/5),5];
int count_0 = 1;
int count_1 = 1;
int count_2 = 1;
int …Run Code Online (Sandbox Code Playgroud)