Reputation: 337
I wrote an application that reads a text file which consists of numbers, then converts them to a double array, then performs some mathematical calculations on the numbers where I calculate the mean, standard deviation, variance, etc.
My question is how can I resize/set the array to take only the first 50 values if the text file contains a lot of values?
Here is my code:
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.....
Upvotes: 1
Views: 2972
Reputation: 117155
Use Array.Resize
:
else if (data.Length > 50)
{
//limit the array to the first 50 values. Then perform the calculations...
Array.Resize(ref data, 50);
}
This reallocates the array.
Note that this will increase the size of the array if the current size is less than your limit of 50, so you should keep the if (data.Length > 50)
check.
Upvotes: 6
Reputation: 101711
You can't resize the array but you can use Take
method to get first 50 items.
Another way is to read 50 lines in the first place as @Habib mentioned in his comment, you can do that easily using File.ReadLines
method:
string[] readText = File.ReadLines("path").Take(50).ToArray();
Upvotes: 5