Reading CSV file and storing values into an array

后端 未结 19 1470
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

19条回答
  •  灰色年华
    2020-11-22 07:00

    You can't create an array immediately because you need to know the number of rows from the beginning (and this would require to read the csv file twice)

    You can store values in two List and then use them or convert into an array using List.ToArray()

    Very simple example:

    var column1 = new List();
    var column2 = new List();
    using (var rd = new StreamReader("filename.csv"))
    {
        while (!rd.EndOfStream)
        {
            var splits = rd.ReadLine().Split(';');
            column1.Add(splits[0]);
            column2.Add(splits[1]);
        }
    }
    // print column1
    Console.WriteLine("Column 1:");
    foreach (var element in column1)
        Console.WriteLine(element);
    
    // print column2
    Console.WriteLine("Column 2:");
    foreach (var element in column2)
        Console.WriteLine(element);
    

    N.B.

    Please note that this is just a very simple example. Using string.Split does not account for cases where some records contain the separator ; inside it.
    For a safer approach, consider using some csv specific libraries like CsvHelper on nuget.

提交回复
热议问题