Hello! There was a problem changing the format of the variable. I have a class:

public class Parsing { public string FIO { get; set; } public DateTime Date { get; set; } } 

And the code itself:

 string line; StreamReader file = new StreamReader(@"Путь"); List<Parsing> csv = new List<Parsing>(); while ((line = file.ReadLine()) != null) { var csvRow = line.Split(';').Skip(1).ToList(); var objList = new Parsing { FIO = (csvRow[0]), Date = DateTime.Parse(csvRow[1]), }; csv.Add(objList); } 

When I try to change the "Date" field to a date format, I get an error: "This string is not recognized as a valid DateTime value. An unknown word has been detected starting with index 0." I understand that this is due to the fact that my header is of type string, and the fields are already in Datetime format, but how can I get around this, I thought .Skip (1) will help me?

 Вот пример CSV-файла: Дата рождения 12.12.1912 01.01.1901 
  • one
    Before a while call file.ReadLine() once to skip the header. - Alexander Petrov
  • Thank! Understood, helped. - Tibomso
  • one
    A small note. In that century, when files are freely transferred via the Internet, it is not worth expecting that all will be given in the format of the current system language. Instead, it is better to explicitly specify either the date format ( DateTime.ParseExact ) - or pass CultureInfo . - Pavel Mayorov

1 answer 1

In the above code, Skip is called on the result of splitting a line.

That is, in this case, one column is skipped. not a string with a title.

To skip the title bar, you must either read this line once to idle without processing it.

Either use the File.ReadLines method, which returns an IEnumerable<string> and apply Skip to it.

For example:

 List<Parsing> csv = (from line in File.ReadLines(@"Путь").Skip(1) let csvRow = line.Split(';').Skip(1).ToList() select new Parsing { FIO = (csvRow[0]), Date = DateTime.Parse(csvRow[1]), }).ToList(); 
  • What is the most correct way? I suspect the second (: - Tibomso
  • 2
    @Tibomso, they are actually about the same. Perhaps with File.ReadLines it is slightly easier to read. but the essence is the same - Grundy