[Solved] Setting variable types from CSV


Right… Because you can never know what the input will be from the CSV you can’t always try and implicitly convert the string to a DateTime and because you want to do the convert of a string within the select a way to do this is an extension method.

  public static class StringExtensions
  {
    public static DateTime TryParseDate(this string strToParse)
    {
      DateTime dt = new DateTime();
      DateTime.TryParse(strToParse, out dt);
      return dt;
    }
  }

Then when you want to convert in the select do it like this:

  var csv = from line in File.ReadAllLines("C:/file.csv")
            let customerRecord = line.Split(',')
            select new Customer()
                {
                  contactID = customerRecord[0],
                  surveyDate = customerRecord[1].TryParseDate(),
                  project = customerRecord[2],
                  projectCode = customerRecord[3]
                };

You have your own method. Hope this helps and works for you.

The string you want to parse will be passed to the method and then you can handle it and return a valid date time, handling incorrect inputs.

http://msdn.microsoft.com/en-us/library/bb383977.aspx

See this link for an explanation

3

solved Setting variable types from CSV