[英]Check if daylist has several days in a row
我在用C#編程。 我得到了DateTimes
的列表,可能是這樣的(我只對日子感興趣):
12/07/2013,
12/07/2013,
12/06/2013,
12/05/2013,
12/04/2013,
12/04/2013,
11/11/2013,
11/10/2013,
11/04/2013.
換句話說,日期清單可以包含更多相同的日期。 這些日子代表着測量,那就是為什么它可以包含更多的同一天。 我需要檢查清單是否連續3天 :
11/11/2013,
11/10/2013,
11/09/2013.
我的代碼如下所示:
public static void longTimeAnalyse(string cpr)
{
List<DateTime> dayList = getDaylist(cpr);
dayList.sort();
DateTime current = DateTime.now.Date;
if(dayList.count() != 0)
{
//check in the dayList if there is any days in a row?? How do i do that?
}
}
這是一個擴展方法,該方法將返回集合中任意數量的連續天數:
static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<DateTime>> GetConsecutiveDays(this IEnumerable<DateTime> data,
int consecutiveDayCount)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
if (consecutiveDayCount < 2)
{
throw new ArgumentException("consecutiveDayCount should be greater than 1");
}
var days = data.Select(item => item.Date).Distinct().OrderBy(item => item);
return days.Select((day, index) => days.Skip(index).Take(consecutiveDayCount).ToList())
.Where(group => group.First().AddDays(consecutiveDayCount - 1) == group.Last());
}
}
測試方法(使用NUnit和FluentAssertions):
[TestFixture]
public class ConsecutiveDaysTests
{
[Test]
public void ConsecutiveDayTest()
{
var dayList = new List<DateTime>
{
new DateTime(2013,12,07),
new DateTime(2013,12,07),
new DateTime(2013,12,06),
new DateTime(2013,12,05),
new DateTime(2013,12,04),
new DateTime(2013,12,04),
new DateTime(2013,11,11),
new DateTime(2013,11,10),
new DateTime(2013,11,04)
};
var result = dayList.GetConsecutiveDays(3).ToList();
result.Should().HaveCount(2);
result.First().ShouldBeEquivalentTo(new[]{new DateTime(2013,12,06),
new DateTime(2013,12,05),
new DateTime(2013,12,04)});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.