简体   繁体   中英

Multiple delete in csv rows by dates

To pursue my goal of deleting multiple lines in csv file. My idea is to get the dates between two dates that are not include for deletion. But how can I iterate days between two dates and get there values to string and used to my code for evaluating the csv file that contains this field.

  private void button2_Click(object sender, EventArgs e)
  {
    DateTime start = new DateTime(01 / 25 / 2015);
    DateTime end = new DateTime(01 / 27 / 2015);

    var dates = new List<DateTime>();

    for (var dt = start; dt <= end; dt = dt.AddDays(1))
    {
      dates.Add(dt);

      var oldLines = System.IO.File.ReadAllLines(txtFileName.Text);
      var newLines = oldLines.Where(line => 
      line.Contains(dates.ToString()));          
      System.IO.File.WriteAllLines(txtFileName.Text, newLines);

      newLines = oldLines.Select(line => new

        {
            Line = line,
            Words = line.Split(' ')
        })
         .Where(lineInfo => lineInfo.Words.Contains(dates.ToString()))
         .Select(lineInfo => lineInfo.Line);
     }
  } 

INPUT:

"EmployeeCode","Date","Time","Type"
"3434","01/22/2013","07:54","0"
"3023","01/23/2014","07:54","0"
"2897","01/24/2015","07:54","0"
"3734","01/25/2015","07:54","0"
"3168","01/26/2015","07:54","0"
"4863","01/26/2015","07:55","0"
"2513","01/27/2015","07:55","0"
"2582","01/27/2015","07:55","0"

OUTPUT:

"EmployeeCode","Date","Time","Type"
"3734","01/25/2015","07:54","0"
"3168","01/26/2015","07:54","0"
"4863","01/26/2015","07:55","0"
"2513","01/27/2015","07:55","0"
"2582","01/27/2015","07:55","0"

Suggestions, comments, sharing codes and ideas are highly appreciated.

A more typical way to do it would be to look over all the lines, extract the relevant parts, convert them to actual dates and compare them to your start and end dates with regular inequalities.

private void button2_Click(object sender, EventArgs e)
{
    DateTime start = new DateTime(2015,01,26);
    DateTime end = new DateTime(2015,01,27);

    var oldLines = System.IO.File.ReadAllLines(txtFileName.Text);
    var newLines = oldLines
        .Select(line => new { line, date = DateTime.Parse(line.Split(',')[1]) })
        .Where(line => line.date > start and line.date < end)
        .Select(line => line.line)
        .ToArray();

    System.IO.File.WriteAllLines(txtFileName.Text, newLines);
}

This does not account for the header line, but you can handle that separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM