Reading CSV file and storing values into an array

后端 未结 19 1745
猫巷女王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:07

    If you need to skip (head-)lines and/or columns, you can use this to create a 2-dimensional array:

        var lines = File.ReadAllLines(path).Select(a => a.Split(';'));
        var csv = (from line in lines               
                   select (from col in line
                   select col).Skip(1).ToArray() // skip the first column
                  ).Skip(2).ToArray(); // skip 2 headlines
    

    This is quite useful if you need to shape the data before you process it further (assuming the first 2 lines consist of the headline, and the first column is a row title - which you don't need to have in the array because you just want to regard the data).

    N.B. You can easily get the headlines and the 1st column by using the following code:

        var coltitle = (from line in lines 
                        select line.Skip(1).ToArray() // skip 1st column
                       ).Skip(1).Take(1).FirstOrDefault().ToArray(); // take the 2nd row
        var rowtitle = (from line in lines select line[0] // take 1st column
                       ).Skip(2).ToArray(); // skip 2 headlines
    

    This code example assumes the following structure of your *.csv file:

    CSV Matrix

    Note: If you need to skip empty rows - which can by handy sometimes, you can do so by inserting

        where line.Any(a=>!string.IsNullOrWhiteSpace(a))
    

    between the from and the select statement in the LINQ code examples above.

提交回复
热议问题