0

For the below code, when i display date from the "for" loop, I get the expected answer but when I store the date in list, I get some other output.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class dateshow
    {
        static void Main(string[] args)
        {
            List<DateTime> allDates = new List<DateTime>();
            DateTime startDate = Convert.ToDateTime("2018-03-03");
            DateTime endDate = Convert.ToDateTime("2018-03-15");
            for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
            {
               allDates.Add(date);
               
               Console.WriteLine(date);

               Console.WriteLine(allDates);  //ERROR : doesnt display the dates, instead displays System.Collections.Generic.List`1[System.DateTime]

            }
        }
    }
}

Where am I going wrong?

Katelyn Raphael
  • 253
  • 2
  • 4
  • 16
  • Use a `for-loop` to iterate over the generated list and output its values. – croxy Apr 18 '19 at 09:39
  • Or use `string.Join`, e.g. `Console.WriteLine(string.Join(',', allDates))`. Although I'd be surprised if you wanted to do that *inside* the loop. – Jon Skeet Apr 18 '19 at 09:40
  • Use following : Console.WriteLine(string.Join(",", allDates.Select(x => x.ToString()))); – jdweng Apr 18 '19 at 09:43

2 Answers2

1

allDates is a list of DateTime objects, that's why you get the following:

System.Collections.Generic.List`1[System.DateTime]

You need to iterate through the allDates variable separately.

foreach (var date in allDates)
{
     Console.WriteLine(date.ToString());
}
umutesen
  • 2,523
  • 1
  • 27
  • 41
1

This way:

    static void Main(string[] args)
    {
        List<DateTime> allDates = new List<DateTime>();
        DateTime startDate = Convert.ToDateTime("2018-03-03");
        DateTime endDate = Convert.ToDateTime("2018-03-15");
        for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
        {
            allDates.Add(date);

            Console.WriteLine(date);

            allDates.ForEach(x => Console.WriteLine(x));
        }
    }

Or:

    static void Main(string[] args)
    {
        List<DateTime> allDates = new List<DateTime>();
        DateTime startDate = Convert.ToDateTime("2018-03-03");
        DateTime endDate = Convert.ToDateTime("2018-03-15");
        for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
        {
            allDates.Add(date);

            Console.WriteLine(date);

            Console.WriteLine(string.Join(",", allDates));
        }
    }
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32