我用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?
}
}
答案 0 :(得分:1)
这是一个扩展方法,它将在集合中返回任意数量的连续日期:
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)});
}
}