Visual C#,两个日期之间的日期数组 [英] Visual C#, An array of Dates between two Dates

查看:435
本文介绍了Visual C#,两个日期之间的日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名为 dtp1 dtp2 DateTimePicker 控件>。我希望获得这两天之间的日期数组: dtp1.Date.Value< = x< = dtp2.Date.Value

I have 2 DateTimePicker controls named dtp1 and dtp2. I wish to get an array of dates between those 2 days: dtp1.Date.Value <= x <= dtp2.Date.Value.

我目前使用进行循环来完成这样的任务,但这不是一种非常有效的处理方式:

I currently use for loop to achieve such a task, but this is not a very efficient way to do things:

int c = (int)(dtp2.Value.Date-dtp1.Value.Date).TotalDays + 1;
DateTime[] d = new DateTime[c];

for (int i = 0; i < c; i++)
{
    d[i] = dtp1.Value.Date.AddDays(i);
}

是否有更好和简洁的方法来实现相同的结果?

Is there any better and concise way to achieve the same result?

推荐答案

我建议您使用列表代替数组,并且您可以使用 Enumarable.Range

I advise you to use lists instead arrays and u can use Enumarable.Range

var startDate = new DateTime(2013, 1, 25);
var endDate = new DateTime(2013, 1, 31);
int days = (endDate - startDate).Days + 1; // incl. endDate 

List<DateTime> range = Enumerable.Range(0, days)
    .Select(i => startDate.AddDays(i))
    .ToList();

您可以了解有关列表的更多信息此处

You can learn much more about Lists here

这篇关于Visual C#,两个日期之间的日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆