我想将一个double值数组拆分成更小的数组块...例如,假设我有一个无限大小的数组test = {x0,x1,x2,x3,x4,x5,x6,x7, ...}我希望将它们分成3个单独的数组,其中a = {x0,x3,x6,x9,...},b = {x1,x4,x7,x10,..}和c = {x2 ,X5,X8,X11,..} ..
我试过,但它没有运行..我不确定是什么错误?有没有更简单的方法来做到这一点?
class Program
{
static void Main(string[] args)
{
double[] test = { 0.2, 1.4, 2.45, 3.66, 4.34, 5.8, 6.9, 7.56, 8.899, 9.232, 10.1, 11.1, 12.45,13.87,14.8,15.78};
double[] array = double [0];
double[] array1 = double [0];
double[] array2 = double [0];
for (int i = 0; i <= test.Length; i++)
{
for (int j = 0; j < test.Length; j=j+3)
{
array[i] = test[j];
}
}
for (int i = 0; i <= test.Length; i++)
{
for (int j = 1; j < test.Length; j = j + 3)
{
array1[i] = test[j];
}
}
for (int i = 0; i <= test.Length; i++)
{
for (int j = 2; j < test.Length; j = j + 3)
{
array2[i] = test[j];
}
}
foreach (int item in array)
{
Console.WriteLine(item);
}
}
}
答案 0 :(得分:2)
LINQ方法Where
有一个带索引参数的重载,你可以使用Skip
,那个重载和模数运算符来实现这个目的:
double[] test = { 0.2, 1.4, 2.45, 3.66, 4.34, 5.8, 6.9, 7.56, 8.899, 9.232, 10.1, 11.1, 12.45, 13.87, 14.8, 15.78 };
var first = test.Skip(0).Where((x, i) => i%3 == 0);
var second = test.Skip(1).Where((x, i) => i%3 == 0);
var third = test.Skip(2).Where((x, i) => i%3 == 0);
在示例中,i
是项目的索引。执行i % 3
会返回每三个项目。上面的代码生成了IEnumerable<double>
类型的集合。如果您需要double[]
,请在每个号码上拨打ToArray
。
作为警告,如果您要多次迭代这些结果,您需要在每个结果上调用ToArray
或ToList
。如果不这样做,test
数组将每次迭代,这是非常低效的。
答案 1 :(得分:1)
你可以像这样利用linq的力量:
double[] test = { 0.2, 1.4, 2.45, 3.66, 4.34, 5.8, 6.9, 7.56, 8.899, 9.232, 10.1, 11.1, 12.45, 13.87, 14.8, 15.78 };
var numberOfArrays = 3;
var sublists = test.Select((i, idx) => new { Item = i, Index = idx })
.GroupBy(x => x.Index % numberOfArrays)
.Select(g => g.Select(x => x.Item).ToArray())
.ToList();
上面的解决方案允许您指定数组的数量,并相应地将原始数组拆分为数组列表。这是通过使用模数运算符实现的,用%
符号表示。
答案 2 :(得分:1)
Altough LINQ为您的问题提供了真正优雅的解决方案,它们有点矫枉过正。此外,我认为在尝试使用c#的更多高级功能之前,您需要首先掌握一些基本概念。
首先:
double[] array = double [0];
实际上做的是创建一个空的双精度数组,事实上,它会给你一个语法错误,你的代码应该是double[] array = new double [0];
。你真正想要的是使用List:
List<double> array = new List<double>();
这将创建您真正想要的集合。要将项目附加到此集合,请使用以下内容(同样,消除外部循环,它不应该在那里):
for (int j = 0; j < test.Length; j = j + 3)
{
array.Add(test[j]);
}
你的最后一个foreach循环不应该是读取,它应该是读取双打
foreach (double item in array)
{
Console.WriteLine(item);
}
应用这些更改,您的代码将按预期工作:)。
最后,你不需要3个单独的循环来完成这项工作,你可以在一个循环中填充3个数组(或任意数量的数组),但是那个留给你。
答案 3 :(得分:0)
这里有一些错误:
这意味着“创建一个数组为零的项目”。考虑到要填充这些数组,应使用大于零的数字。 Test.length / 3
似乎是您示例中的正确数字。
double[] array = double [0]; // This is wrong
// Try this instead:
var array = new double[test.Length / 3]; // div 3 because you have 3 output arrays
然后在这里,你想要将你的外部循环限制为array.Length,而不是test.Length:
for (int i = 0; i < array.Length; i++)
{
array[i] = test[i*3];
}