开发者

C# DateTime manipulation

开发者 https://www.devze.com 2022-12-26 04:16 出处:网络
I have a list of dates for an event in the following format 13/04/2010 10:30:00 13/04/2010 13:30:00 14/04/2010 10:30:00

I have a list of dates for an event in the following format

13/04/2010 10:30:00
13/04/2010 13:30:00
14/04/2010 10:30:00
14/04/2010 13:30:00
15/04/2010 10:30:00
15/04/2010 13:30:00
16/04/2010 10:30:00
17/04/2010 11:00:00
17/04/2010 13:30:00
17/04/2010 15:30:00

How can i have the list be output, so that the date is only displayed once f开发者_开发知识库ollowed by the times for that date, so the above list would look like something like this:

13/04/2010 
10:30:00
13:30:00

14/04/2010 
10:30:00
13:30:00

15/04/2010 
10:30:00
13:30:00

16/04/2010 
10:30:00

17/04/2010 
11:00:00
13:30:00
15:30:00


Well I don't know about the display side, but the grouping side is easy if you're using .NET 3.5+:

var groups = list.GroupBy(dateTime => dateTime.Date);

foreach (var group in groups)
{
    Console.WriteLine("{0}:", group.Key);
    foreach(var dateTime in group)
    {
        Console.WriteLine("  {0}", dateTime.TimeOfDay);
    }
}


        List<DateTime> dateTimes = new List<DateTime>();
        Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
        foreach (DateTime t in dateTimes)
        {
            if (!data.ContainsKey(t.ToShortDateString()))
            {
                data.Add(t.ToShortDateString(), new List<string>());
            }

            data[t.ToShortDateString()].Add(t.ToShortTimeString());
        }

        foreach (string key in data.Keys)
            data[key].Sort();

        foreach (var pair in data)
        {
            Console.WriteLine(pair.Key);
            foreach (string time in pair.Value)
                Console.WriteLine(time);

            Console.WriteLine();
        }


If you have your dates in something like a List<DateTime> then you could do this:

DateTime dtTemp = DateTime.MinValue;
StringBuilder sb = new StringBuilder();
foreach(DateTime dt in MyDateList)
{
    if (dt == dtTemp) sb.AppendLine(dt.ToString("HH:mm:ss"));
    else
    {
        dtTemp = dt;
        sb.AppendLine();
        sb.AppendLine(dt.ToString("dd/MM/yyyy HH:mm:ss"));
    }
}
Console.WriteLine(sb.ToString().Trim());

Edit: Trim output to eliminate blank first line.

0

精彩评论

暂无评论...
验证码 换一张
取 消