Read CSV with Linq

前端 未结 2 567
夕颜
夕颜 2021-01-07 06:08

I have the following lines (more, but this sample is fine) in a CSV file.

Date,Open,High,Low,Close,Volume,Adj Close
2012-11-01,77.60,78.12,77.37,78.05,186200         


        
相关标签:
2条回答
  • 2021-01-07 06:29

    You can try this:-

                var lines = File.ReadAllLines(@"Linq.csv").Select(x => x.Split(','));
                //Considering each line contains same no. of elements
                int lineLength = lines.First().Count();  
                var CSV = lines.Skip(1)
                           .SelectMany(x => x)
                           .Select((v, i) => new { Value = v, Index = i % lineLength })
                           .Where(x => x.Index == 2 || x.Index == 3)
                           .Select(x => x.Value);
                foreach (var data in CSV)
                {
                    Console.WriteLine(data);
                }
    

    Steps:-

    Step 1 - Read all lines from CSV file and split them by Comma(,) which will result in an array os strings with every value.

    Step 2 - Skip the first array (which is holding the headers), then use SelectMany to flatten the list into one, Next you need to set the index for each set(in the flatten list)similar, which I am doing with Select opertaor, the last thing left is filtering & selecting the item.

    0 讨论(0)
  • 2021-01-07 06:30

    You can try bellow code for function 1

    var stuff = from l in File.ReadAllLines(filename)
            let x = l.Skip(1).Split(new [] {',', ' '}, StringSplitOptions.RemoveEmptyEntries)
                     .Select(s => s)
                     .select new
                        {
                          second= s[1],
                          third= s[2]
                        };
    
    0 讨论(0)
提交回复
热议问题