我现在被困了一段时间,现在需要你的帮助.
我想在每个月的第四个星期日显示一个下拉菜单,比如从2010年9月1日到2011年8月31日
我只想在下拉列表中第四个星期天,如何使用asp.net C#
问候
这是一种使用一点LINQ的方法,并且知道第四个星期日将在一个月的22和28之间发生,包括在内.
DateTime startDate = new DateTime(2010, 9, 1);
DateTime endDate = startDate.AddYears(1).AddDays(-1);
List<DateTime> fourthSundays = new List<DateTime>();
DateTime currentDate = startDate;
while (currentDate < endDate)
{
// we know the fourth sunday will be the 22-28
DateTime fourthSunday = Enumerable.Range(22, 7).Select(day => new DateTime(currentDate.Year, currentDate.Month, day)).Single(date => date.DayOfWeek == DayOfWeek.Sunday);
fourthSundays.Add(fourthSunday);
currentDate = currentDate.AddMonths(1);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将其绑定List<DateTime>到下拉列表或跳过列表本身,以便在将项目生成到下拉列表时添加项目,如下所示.
yourDropdown.Items.Add(new ListItem(fourthSunday.ToString()));
Run Code Online (Sandbox Code Playgroud)
对于咯咯笑声,您可以在LINQ语句中完成整个操作并跳过(大部分)变量.
DateTime startDate = new DateTime(2010, 9, 1);
IEnumerable<DateTime> fourthSundays =
Enumerable.Range(0, 12)
.Select(item => startDate.AddMonths(item))
.Select(currentMonth =>
Enumerable.Range(22, 7)
.Select(day => new DateTime(currentMonth.Year, currentMonth.Month, day))
.Single(date => date.DayOfWeek == DayOfWeek.Sunday)
);
Run Code Online (Sandbox Code Playgroud)