You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#读取CSV时DateTime字段为空如何返回"Never"字符串?

解决CSV空日期输出"Never"的问题

这是个很常见的初学者场景,我来帮你搞定这个问题。核心矛盾在于DateTime是值类型,它无法存储null值——当CSV里的日期字段为空时,DateTime.TryParse会返回默认的Mon Jan 1, 0001。我们可以通过以下几步修改来实现你要的"Never"输出效果:

步骤1:将日期字段改为可空类型

把GroceryItem类里的ExpirationDate改成DateTime?(也就是Nullable<DateTime>的简写),这样就能存储"无日期"的状态:

class GroceryItem {
    public string Description { get; private set; }
    public decimal Price { get; set; }
    // 改为可空DateTime,支持存储null值
    public DateTime? ExpirationDate { get; private set; }

    public GroceryItem() { }
    // 构造函数同步修改参数类型
    public GroceryItem(string descr, decimal p, DateTime? date) {
        Description = descr;
        Price = p;
        ExpirationDate = date;
    }
}

步骤2:读取CSV时正确处理空日期

在读取CSV行的时候,不仅要判断解析是否成功,还要主动处理字段为空的情况——如果lineElement[2]是空字符串,直接把ExpirationDate设为null:

// 替换原来的读取逻辑部分
while(sr.Peek() > 0) {
    lineData = sr.ReadLine();
    string[] lineElement = lineData.Split(',');
    string description = lineElement[0];
    decimal price = 0;
    DateTime? expirationDate = null;

    // 解析价格(保持原有逻辑)
    decimal.TryParse(lineElement[1], out price);
    
    // 处理日期:仅当字段非空时才尝试解析
    if (!string.IsNullOrWhiteSpace(lineElement[2])) {
        DateTime parsedDate;
        if (DateTime.TryParse(lineElement[2], out parsedDate)) {
            expirationDate = parsedDate;
        }
    }

    items.Add(new GroceryItem(description, price, expirationDate));
}

步骤3:打印时判断日期状态输出对应内容

在ConsolePrinter.PrintCollection方法里,判断ExpirationDate是否有值,有值就格式化输出日期,无值则输出"Never":

public static void PrintCollection(GroceryItemCollection items) {
    foreach(GroceryItem item in items) {
        // 核心:根据日期是否存在生成显示文本
        string expirationText = item.ExpirationDate.HasValue 
            ? item.ExpirationDate.Value.ToString("ddd MMM d, yyyy") 
            : "Never";
        
        Console.WriteLine("{0, -20} {1, 8} {2, -28}", 
            item.Description, item.Price, expirationText);
    }
    Console.WriteLine(new string('-', 47));
    Console.WriteLine("{0, -20} {1, 8}", "Total", items.TotalPrice);
}

额外补充:修复TotalPrice属性缺失问题

我注意到你代码里用了items.TotalPrice,但GroceryItemCollection类目前没有这个属性,记得补充一下:

class GroceryItemCollection : List<GroceryItem> {
    // 用LINQ实现总价计算
    public decimal TotalPrice => this.Sum(item => item.Price);
}

这样修改后,当CSV里的"Expires"列是空值时,程序就会输出"Never",而不是默认的初始日期了。

内容的提问来源于stack exchange,提问作者ishop6688

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:11:25