C # DateTime переменная читать CSV-файл, если он пуст, как вернуть строковое сообщение - PullRequest
1 голос
/ 09 июня 2019

Я новичок в C # и хотел бы задать вопрос.

Как вернуть переменной DateTime строковое сообщение «Никогда», если прочитанные данные из CSV-файла пусты?

Это мой код:

class GroceryItem
{
    public string Description { get; private set; }
    public decimal Price { get; set; }
    public DateTime ExpirationDate { get; private set; }

    public GroceryItem()
    { }

    public GroceryItem(string descr, decimal p, DateTime date)
    {
        Description = descr;
        Price = p;
        ExpirationDate = date;
    }
}

class GroceryItemCollection : List<GroceryItem>

class ConsolePrinter
{
    public static void PrintHeader()
    {
        Console.WriteLine("{0, -20} {1, 8} {2, -28}", "Grocery Item", "Price", "Expires");
        Console.WriteLine(new string('-', 47));
    }

    public static void PrintCollection(GroceryItemCollection items)
    {
        foreach(GroceryItem item in items)
        {
            Console.WriteLine("{0, -20} {1, 8} {2, -28}", 
                item.Description, item.Price, item.ExpirationDate.ToString("ddd MMM d, yyyy"));                               
        }

        Console.WriteLine(new string('-', 47));
        Console.WriteLine("{0, -20} {1, 8}", "Total", items.TotalPrice);
    }
}

class Program
{
    static void Main(string[] args)  
    {
        string path;           

        if(args.Length > 0)
        {
            path = args[0];
        }
        else
        {
            Console.WriteLine("No file found");
            return;
        }

        StreamReader sr = null;
        string lineData;
        GroceryItemCollection items = new GroceryItemCollection(); 

        if (File.Exists(path))
        {
            try
            {
                using(sr = new StreamReader(path))
                {
                    while(sr.Peek() > 0)
                    {
                        lineData = sr.ReadLine();
                        string[] lineElement = lineData.Split(',');                            

                        string description;
                        decimal price;
                        DateTime expirationDate;
                        description = lineElement[0];
                        bool priceSuccess = decimal.TryParse(lineElement[1], out price);

                        bool expirationDateSuccess = DateTime.TryParse(lineElement[2], out expirationDate);
                        items.Add(new GroceryItem(description, price, expirationDate));
                    }                        

                    ConsolePrinter.PrintHeader();
                    ConsolePrinter.PrintCollection(items);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n{ex.Message}\n");
            }
        }
    }
} 

Ожидаемый возврат "Продуктовый товар", "Цена", "Срок действия истекает" из данных CSV

Как исправить мой код выше и вернуть Expires данные строковое сообщение «Никогда», если данные CSV пустые?

Мой код возвращает дату по умолчанию «Пн Ян 1, 0001»

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...