如何将CSV文件读入int [] C#

时间:2014-10-13 23:43:47

标签: c# string file matrix int

我有一个文件a.csv,其中包含n×n维的方阵,格式如下:

1,2,3
4,5,6
7,8,9

我想把它读成一个int [],比如:

StreamReader csv = new StreamReader("a.csv");
        int n = 3
        string[] lines = new string[n];
        int[] intlines = new int[n]
        int q = 0;
        bool exiting = false;
        do
        {
            if (csv.ReadLine() != "")
            {
                exiting = true;
            }

            if (exiting == false)
            {
                lines[q] = (((csv.ReadLine()).Split(",")).ToString());
                q++;
            }
        }
        while (exiting == false);           
        Console.WriteLine("Finished Reading!");
        System.Threading.Thread.Sleep(500);
        int q2 = 0;         
        foreach (string s in lines)
        {
            Console.WriteLine("lines: {0}", s);
            intlines[q2] = int.Parse(s);
        }
        foreach (int i in intlines)
        {
            Console.WriteLine("intlines: {0}", i.ToString());
        }
        Console.ReadKey();

目前,由于编译器正在讨论char []的问题,因此存在问题。无论如何,我如何将水平线和垂直线读入2维int []? 谢谢。

3 个答案:

答案 0 :(得分:2)

试试这个:

using (var sr = new StreamReader("a.csv"))
{
    var myArray = sr.ReadToEnd()
        .Split('\n')
        .SelectMany(s => s.Split(',')
            .Select(x => int.Parse(x)))
        .ToArray<int>();

    foreach(var x in myArray)
        Console.WriteLine (x);
}

答案 1 :(得分:0)

你应该考虑在nuget和github上使用Josh Close的CSVhelper https://github.com/JoshClose/CsvHelper

它是一个很棒的图书馆。

答案 2 :(得分:0)

来自@ Malik的答案的另一个变种。

string[] data = File.ReadAllText(@"D:\code\cs\sample.txt")
                    .Split(new char[] { ',','\r','\n' });

int[] ints = data.Where(x => x.Count() != 0)
                 .Select(x => int.Parse(x)).ToArray();
foreach(var e in ints)
{
   Console.WriteLine(e);
}