首页 新闻 搜索 专区 学院

请问如何获取一个时间段内有多少个星期X

0
[已解决问题] 解决于 2012-04-16 16:32

        /// <summary>
        /// 根据时间段获取每星期X的总数
        /// </summary>
        /// <param name="beginDateTime">开始时间</param>
        /// <param name="endDateTime">结束时间</param>
        /// <param name="week">星期几 0:星期日</param>
        /// <returns></returns>
        public static int GetWeekCount(DateTime beginDateTime, DateTime endDateTime, List<DayOfWeek> weekList)
        {

        }

        

       如何让这个单元测试相等呀?

            List<DayOfWeek> list = new List<DayOfWeek>();
            list.Add(DayOfWeek.Tuesday);
            list.Add(DayOfWeek.Wednesday);
//从2012-5-1日到2012-5-31 日有10天符合星期二或星期三          TestHelper.Test(DateTimeHelper.GetWeekCount(DateTime.Parse("2012-5-1"), DateTime.Parse("2012-5-31"), list) == 10);

无名小卒的主页 无名小卒 | 菜鸟二级 | 园豆:209
提问于:2012-04-16 12:59
< >
分享
最佳答案
0
public static int GetWeekCount(DateTime begin, DateTime end, List<DayOfWeek> weekList)
{
       return Enumerable.Range(0, (end - begin).Days)
           .Count(n => weekList.Contains(begin.AddDays(n).DayOfWeek));
}
奖励园豆:5
水牛刀刀 | 大侠五级 |园豆:6350 | 2012-04-16 15:12
改成这个了,谢谢

public
static int GetWeekCount(DateTime begin, DateTime end, List<DayOfWeek> weekList){ return Enumerable.Range(0, (end.AddDays(1) - begin).Days) .Count(n => weekList.Contains(begin.AddDays(n).DayOfWeek));}

但是性能还是比较低
无名小卒 | 园豆:209 (菜鸟二级) | 2012-04-16 16:36
其他回答(1)
0

获取一段时间内有多少个周几,你这样写试试呢:

       public static int GetWeekCount(DateTime beginDateTime, DateTime endDateTime, List<DayOfWeek> weekList)
       {
           int num = 0;
           for (; beginDateTime < endDateTime; beginDateTime = beginDateTime.AddDays(1))
           {
             foreach ( DayOfWeek dow in weekList)
             {
                 if (beginDateTime.DayOfWeek == dow)
                     num++;
             }
           }
           return num;
       }

qia | 园豆:164 (初学一级) | 2012-04-16 13:20

这样的话性能不太好吧。

支持(0) 反对(0) 无名小卒 | 园豆:209 (菜鸟二级) | 2012-04-16 13:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册