我需要更改代码以了解txt文件中数组的维度,我的代码中的问题是我只能获得2d数组的维度,例如2 * 2,3 * 3 ......但我需要例如3 * 1
static double[,] ParseNumberFile(string filename)
{
// read data from txt file
string fileContent = File.ReadAllText(filename);
// first put all lines into an string array
string[] allLines = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
// calculate 2D array's dimension lengths, and initialize the 2Darray
int rowCount = allLines.Length;
int columnCount = allLines.Length;
int i = 0, j = 0;
double[,] result = new double[rowCount, columnCount];
foreach (var row in fileContent.Split(new char[] { '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = double.Parse(col.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo);
j++;
}
i++;
}
return result;
}
答案 0 :(得分:1)
您可以使用通用列表:
List<List<double>> result = new List<List<double>>();
foreach (var row in fileContent.Split(new char[] { '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
List<double> list = new List<double>()
foreach (var col in row.Trim().Split(' '))
{
list.Add(double.Parse(col.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo));
}
result.Add(list);
}
答案 1 :(得分:1)
Linq方式:
double[][] doubles = File.ReadAllLines("foo.txt").
Where(line => !string.IsNullOrWhiteSpace(line)).
Select(line => line.Split(' ').Select(double.Parse).ToArray()).
ToArray();
为您节省大量代码;)