如何将CSV文件的内容添加到double[]数组中?

v440hwme  于 2023-05-20  发布在  其他
关注(0)|答案(3)|浏览(149)

我正在尝试从CSV文件中读取并将内容添加到double[]数组中。
文件的内容似乎正确地添加到字符串数组中,但当试图解析为双精度数组时,它会出现错误:
System.FormatException:'输入字符串的格式不正确。'
计划内容:

string[] csvFile = System.IO.File.ReadAllText(@"C:\\Users\\...\\Documents\\CSVExample.csv").Split(',');
double[] dblArray = Array.ConvertAll(csvFile, double.Parse);
foreach (double d in dblArray)
{
    System.Console.WriteLine(d);
}

CSV内容:

10,14,7,1,19,4,15,17,16,5,13,8,18,2,12,9,3,20,6,11
6,10,13,17,4,11,5,14,19,3,9,20,15,8,1,2,18,7,12,16
13,5,11,6,4,10,9,17,19,14,1,16,12,8,7,18,20,2,15,3
2,5,4,14,20,15,3,13,7,1,12,8,19,18,11,10,9,6,16,17

我也尝试过:

double[] dblArray = dblArray.Select(s => Convert.ToDouble(s)).ToArray();

发生了与上述相同的错误。

3wabscal

3wabscal1#

换行符是拆分后字符串的一部分,您可以使用以下方法:

string[] csvFile = System.IO.File.ReadLines(@"C:\\Users\\...\\Documents\\CSVExample.csv")
    .SelectMany(line => line.Split(','))
    .ToArray();
// .. rest of code same

另一种方法是按两个字符拆分:

string[] csvFile = System.IO.File.ReadAllText(@"C:\\Users\\...\\Documents\\CSVExample.csv")
    .Split(new[]{',', '\n'}, StringSplitOptions.None)
    .ToArray();
ssm49v7z

ssm49v7z2#

您可以将csv文件中的所有行读取到一个字符串数组中,并遍历每行,使用逗号作为分隔符拆分该行的元素,然后从每个元素中解析double元素。

var lines = File.ReadLines(@"C:\\\\Users\\\\...\\\\Documents\\\\CSVExample.csv");
//get the number of lines in the csv
var numLines = lines.ToList().Count;    
//get the number of individual numbers in a single line
var elCount = lines.ToList()[0].Split(",").Length;
//get the size of your double array
var size = numLines * elCount;
//initialize you double array
var darray = new double[size];
//initialize a variable to loop through the array with
var p = 0;
//iterate through the csv and parse double elementss and add to the array
foreach(var line in lines)
{
    var values = line.Split(',');   
    foreach(var val in values)
    {
        darray[p++] = Double.Parse(val);    
    }
}
//TO DO with the double array
//print the contents of the array to the screen
for(int i=0; i < darray.Length; i++)
{
    if(i % elCount == 0)
    {
        //break a line
        Console.WriteLine("\n");
    }
    Console.Write(darray[i]+" ");
}
/*

10 14 7 1 19 4 15 17 16 5 13 8 18 2 12 9 3 20 6 11

6 10 13 17 4 11 5 14 19 3 9 20 15 8 1 2 18 7 12 16

13 5 11 6 4 10 9 17 19 14 1 16 12 8 7 18 20 2 15 3

2 5 4 14 20 15 3 13 7 1 12 8 19 18 11 10 9 6 16 17
*/
ovfsdjhp

ovfsdjhp3#

尝试以下操作:

const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            List<double> dblArray = new List<double>();
            StreamReader reader = new StreamReader(FILENAME);
            string line = "";
            while((line = reader.ReadLine()) != null)
            {
                double[] dbl = line.Split(new char[] { ',' }).Select(x => double.Parse(x)).ToArray();
                dblArray.AddRange(dbl);
            }

        }

相关问题