如何读取文本文件并将数据添加到C#中的int数组? [英] How to read a text file and add the data to a int array in C#?

查看:139
本文介绍了如何读取文本文件并将数据添加到C#中的int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取包含用逗号分隔的数字的文本文件。当我使用 File.Readline()阅读时,我将其转到 string [] 。我需要将其转换为int数组,但它会给出错误。

I'm trying to read a text file which contains numbers separated by a comma. When I read using File.Readline() I get it to a string[]. I need to convert it in to a int array but it gives an error.

文本文件的内容:


146429,143689,144380, 141523,139572,136930,133714,130011,125843,121110,115974,110363,104367,97909,91245,84218,77008,69626,62058,54445,46942,39436,32146,24932,18359,12601,9039,9776, 13638,18314,23221,27728,32142,35941,39577,42657,45692,48180

146429,143689,144380,141523,139572,136930,133714,130011,125843,121110,115974,110363,104367,97909,91245,84218,77008,69626,62058,54445,46942,39436,32146,24932,18359,12601,9039,9776,13638,18314,23221,27728,32142,35941,39577,42657,45692,48180

我的代码:

while ((line = sr.ReadLine()) != null)
{
    string[] values = line.Split(new string[] { " , " }, StringSplitOptions.None); 

    for (int i = 0; i < values.Length; i++)
    {
        // Console.WriteLine(values[i]);
        valArr[LineCount][i] = Convert.ToInt64(values[i]); // error
    }

    LineCount++;
}


推荐答案

使用 List 可以帮助您,并使用 StringSplitOptions.RemoveEmptyEntries 来阻止 null异常 in Convert.ToInt64

Using List can help you, and use StringSplitOptions.RemoveEmptyEntries to prevent null exception in Convert.ToInt64

var lineArray = new List<List<Int64>>();

foreach (var lineString in File.ReadAllLines("path"))
{
    var line = new List<Int64>();
    string[] values = lineString.Split(new[] { ',', ' ' },  
                                       StringSplitOptions.RemoveEmptyEntries);
    line.AddRange(values.Select(t => Convert.ToInt64(t)));
    lineArray.Add(line);
}

并使用它:

// Array of numbers for specific line
var resultArray = lineArray[lineNumber].ToArray();  

这篇关于如何读取文本文件并将数据添加到C#中的int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆