c# CSV 文件 如何删除日期已过去的行

本文关键字:日期 过去 删除 文件 CSV 何删除 | 更新日期: 2023-09-27 18:31:00

private void Form1_Load(object sender, EventArgs e)
{
     using (StreamReader sr = new StreamReader("1.csv"))
     {
         string headerLine = sr.ReadLine();
         String line;
         while (sr.Peek() != -1) // Just read the first line and do nothing with it... 
         while ((line = sr.ReadLine()) != null)
         {
             string[] parts = line.Split(',');
             string day = parts[3];
             string month = parts[2];
             string year = parts[1];
             string OldDate = (day + "/" + month + "/" + year);
             DateTime dt1 = DateTime.Parse(OldDate);
             DateTime dt2 = DateTime.Now;
             if (dt1.Date >= dt2.Date)
             {
                 MessageBox.Show(dt1 + " still relevant ");                       
             }
             else
             {
                 //  How do I delete rows with a date already passed ?
             }
         }

c# CSV 文件 如何删除日期已过去的行

您可以使用要保留的行重新创建文本文件。使用StreamReader并填充List<string>,或者使用以下 LINQ 方法:

List<string> lines = File.ReadLines("1.csv")
    .Select(l => new{ Line = l, Parts = l.Split(',') })
    .Where(x => x.Parts.Length >= 4)
    .Select(x => new {
        x.Line, 
        Day = x.Parts[3].Trim().TryGetInt32(),
        Month =  x.Parts[2].Trim().TryGetInt32(),
        Year =  x.Parts[1].Trim().TryGetInt32(),
    })
    .Where(x => x.Day.HasValue && x.Month.HasValue && x.Year.HasValue)
    .Select(x => new {x.Line, Date = new DateTime(x.Year.Value, x.Month.Value, x.Day.Value) })
    .Where(x => x.Date >= DateTime.Now)
    .Select(x => x.Line)
    .ToList();
File.WriteAllLines("1.csv", lines);

使用了这个扩展方法,该方法在 LINQ 查询中派上用场,如下所示:

public static int? TryGetInt32(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}
为此

,您需要跟踪通过的日期,在这里,如果它包含当前获取的日期,建议您使用List<DateTime>添加到列表中。因此,"包含为 true"表示日期已经过去了。简而言之,您可以像下面这样使用:

        List<string> linesInFile = File.ReadLines("yourFile.csv").ToList();
        List<DateTime> passedDateList = new List<DateTime>();
        List<string> duplicateLines = new List<string>();
        foreach (var item in linesInFile)
        {
            //extract value for date
            string OldDate = (day + "/" + month + "/" + year);
            DateTime dt1 = DateTime.Parse(OldDate);
            if (passedDateList.Contains(dt1))
            {
                duplicateLines.Add(item);
                // the date is already passed
            }
            else
            {
                // it is no yet passed 
                //Do your task here
                passedDateList.Add(dt1);
            }
        }
        linesInFile = linesInFile.Except(duplicateLines).ToList(); // remove already passed line
        File.WriteAllLines("yourFile.csv", linesInFile); // write back to the file