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 ?
}
}
最佳答案
您可以使用要保留的行重新创建文本文件。要么使用你的 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;
}
关于c# CSV FILE 如何删除日期已过的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34872086/