如何限制/截断数组?

The*_*heo 1 c# arrays

我写了一个应用程序,它读取一个由数字组成的文本文件,然后将它们转换为双数组,然后对我计算平均值,标准偏差,方差等的数字执行一些数学计算.

我的问题是,如果文本文件包含大量值,我如何调整/设置数组只采用前50个值?

这是我的代码:

FileReaderClass fr = new FileReaderClass();
CalculatorClass calc = new CalculatorClass();

string[] readText = fr.ReadFile(fileName);
double[] data = fr.ConvertToDoubleArray(readText);

if (data.Length < 5)
{
    MessageBox.Show("There are not enough data points in this file to perform the calculation.");
    return;
}
else if (data.Length > 50)
{
    //limit the array to the first 50 values. Then perform the calculations...
}
//else perform the calculations.....
Run Code Online (Sandbox Code Playgroud)

dbc*_*dbc 6

用途Array.Resize:

else if (data.Length > 50)
{
    //limit the array to the first 50 values. Then perform the calculations...
    Array.Resize(ref data, 50);
}    
Run Code Online (Sandbox Code Playgroud)

这会重新分配数组.

请注意,如果当前大小小于50的限制,这将增加数组的大小,因此您应该继续if (data.Length > 50)检查.


Sel*_*enç 5

您无法调整数组大小,但可以使用Take方法获取前50个项目.

另一种方法是首先阅读50行,如@Habib在他的评论中提到的,你可以使用File.ReadLines方法轻松地做到这一点:

string[] readText = File.ReadLines("path").Take(50).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • 它不会调整原始数组的大小.它分配一个新的数组.所以我不称之为真正调整大小. (2认同)