【C#】实现一个DateTime集合

题目:

定义一个集合,类型为时间类型。要求集合内容为从今天开始按索引加一天的升序排序(累加的天数为10)。新建控制台应用程序输出刚刚的集合到前台并格式化日期为(2019-xx-xx),判断如果日期day为偶数,则通过报错的方法输出到控制台上,并不影响接下去的输出。错误内容为:当天为偶数位,日期2019-xx-xx

要求:

集合的产生过程必须通过程序,输出和排序必须用linq

实现代码:

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

namespace day01
{
    class DateTimeList
    {
        /// <summary>
        /// 时间集合
        /// </summary>
        public void GetDateTimeList()
        {
            DateTime dateTime = DateTime.Now;
            List<DateTime> list = new List<DateTime>();
            //初始化集合
            for (int i = 0; i < 10; i++)
            {
                //加一天的时间间隔
                dateTime = dateTime.AddDays(1);
                //添加到集合
                list.Add(dateTime);
            }

            //Linq排序
            var linqList = from l in list orderby l ascending select l;
            //Linq输出
            foreach (var value in linqList)
            {
                Console.WriteLine(value.ToString("yyyy-MM-dd"));
            }

            //把所有日期为偶数的元素做异常捕获处理
            foreach (var date in linqList)
            {
                try
                {
                    if (date.Day % 2 == 0)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("当天为偶数位,日期" + date.ToString("yyyy-MM-dd"));
                }
                finally
                {

                }
            }

        }
        static void Main(string[] args)
        {
            DateTimeList dateTimeList = new DateTimeList();
            dateTimeList.GetDateTimeList();
            Console.ReadKey();
        }
    }
}

运行结果:

发布了62 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Yanzudada/article/details/102803726