从文本文件中读取数据作为列表数组

时间:2014-02-15 17:44:10

标签: c#

我想从文件中读取数据作为列表数组但是当我实现此代码时,我发现错误的结果。 这是我的代码,文本文件中的数据与double [] x

中的数据相同
try
        {
            using (StreamReader reader = new StreamReader(@"E:\TestFile.txt"))
            {
                while ((line = reader.ReadLine()) != null)
                    data += line + " ";
            }
            //   Console.WriteLine(data);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        double[] x = new double[100];
        int ind = 0;
        double num = 0;
        for (int i = 0; i < data.Length; i++)
        {
            num *= 10;
            num += data[i] - '0';
            if (data[i] == ' ')
            {
                x[ind++] = num;
                num = 0;
            }
        }
        //  double[] x = { 9, 3, 1, 5, 1, 2, 0, 1, 0, 2, 2, 8, 1, 7, 0, 6, 4, 4, 5 };

1 个答案:

答案 0 :(得分:1)

不完全知道你的文本文件的内容它几乎是一个猜测游戏,但如果它只是由空格或新行分隔的数字,这应该做:

double[] x =
    // Read all lines inside an IEnumerable<string>
    File.ReadAllLines(@"E:\TestFile.txt")
    // Create a single string concatenating all lines with a space between them
    .Aggregate("", (current, newLine) => current + " " + newLine)
    // Create an array with the values in the string that were separated by spaces
    .Split(' ')
    // Remove all the empty values that can be due to multiple spaces
    .Where(s => !string.IsNullOrWhiteSpace(s))
    // Convert each string value into a double (Returning an IEnumerable<double>)
    .Select(s => double.Parse(s))
    // Convert the IEnumerable<double> to an array
    .ToArray();