-3

I have a csv file

Date,Open,High,Low,Close,Volume,Adj Close
2011-09-23,24.90,25.15,24.69,25.06,64768100,25.06
2011-09-22,25.30,25.65,24.60,25.06,96278300,25.06
...

and i have a class StockQuote with fields Date,open,high... How can i make a list of StockQuote object from csv file using linq?

I m trying something like this:`

 stirng[] Data = parser.ReadFields();  
     var query = from d in Data  
    where !String.IsNullorWhiteSpace(d)  
    let data=d.Split(',')  
    select new StockQuote()  
    {  
    Date=data[0],  Open=double.Parse(data [ 1 ] ),
    ...

`

DraganB
  • 1,128
  • 2
  • 10
  • 26

3 Answers3

3

You can do something like this..

var yourData = File.ReadAllLines("yourFile.csv")
                   .Skip(1)
                   .Select(x => x.Split(','))
                   .Select(x => new
                                {
                                    Date= x[0],
                                    Open = double.Parse(x[1]),
                                    High = double.Parse(x[2]),
                                    Low = double.Parse(x[3]),
                                    Close = double.Parse(x[4]),
                                    Volume = double.Parse(x[5]),
                                    AdjClose = double.Parse(x[6])
                                });
Pikoh
  • 7,582
  • 28
  • 53
AKN
  • 416
  • 2
  • 5
0

You should not be using Linq, Regex or the like for CSV parsing. For CSV parsing, use a CSV Parser. Linq and Regex will work exactly until you run into a escaped control character, multiline fields or something of the sort. Then they will plain break. And propably be unfixable.

Christopher
  • 9,634
  • 2
  • 17
  • 31
0

Take a look at this question : Parsing CSV files in C#, with header

The answer mentionning .Net integrated CSV parser seems fine. And no, you don't need Linq for this.

Community
  • 1
  • 1