0

I am new to C# and I have been trying to understand how I can read from a CSV file a specific value. My file has the following format

08/11/2012 01:00:00,28/11/2012 01:00:00,29/11/2012 01:00:00,88,
08/11/2012 01:00:00,29/11/2012 01:00:00,30/11/2012 01:00:00,88,
08/11/2012 01:00:00,30/11/2012 01:00:00,01/12/2012 01:00:00,88,
08/11/2012 01:00:00,01/12/2012 01:00:00,02/12/2012 01:00:00,90.25,
08/11/2012 01:00:00,02/12/2012 01:00:00,03/12/2012 01:00:00,90.25,

I want to read and save to a list as string the last values (i.e 88 90.25, etc). I tried everything that I found until now here to this forum but it is not working in my case.

I want to do this because I want to compare this list with another string list that take this values from an XML file which is produced from another model that I run. Thanks a lot for your help!

**this csv file contains ~55000 lines with the above format.

amigo
  • 155
  • 1
  • 10

3 Answers3

4
var values = File.ReadAllLines("").Select(x => x.Split(new char[] { ',' })[3]);

Small edit - typo. Use this example to test:

  List<string> lines = new List<string>();
  lines.Add("08/11/2012 01:00:00,28/11/2012 01:00:00,29/11/2012 01:00:00,88,");
  lines.Add("08/11/2012 01:00:00,29/11/2012 01:00:00,30/11/2012 01:00:00,88,");
  var values = lines.Select(x => x.Split(new char[] { ',' })[3]);

Retrieves 88, 88 in a list.

LukeHennerley
  • 6,344
  • 1
  • 32
  • 50
0

if your values are like this and don't include "," inside it's values:

TextReader tr1 = new StreamReader(CSVFileName, true);

var Data = tr1.ReadToEnd().Split('\n')
    .Where(l => l.Length > 0)  //nonempty strings
    .Skip(1)               // skip header if it has one
    .Select(s => s.Trim())   // delete whitespace
    .Select(l => l.Split(',')) // get arrays of values
    .Select(l => new { Date_1 = l[0], 
                       Date_2 = l[1], 
                       Date_3 = l[2], 
                       Val = l[3] });

and then you can use this object with foreach or whatever you like.

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
0
double[] numbers = fileText.Split('\n').Select(x => double.Parse(x.Split(',')[3])).ToArray();
string numbersJoined = string.Join(" ", numbers);
Tim S.
  • 55,448
  • 7
  • 96
  • 122