1

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?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Pikachu620
  • 483
  • 4
  • 17
  • 1
    What is wrong with your solution, specifically? Looks fine to me at first glance. – Zer0 May 02 '18 at 02:15
  • You might be interested in this: https://stackoverflow.com/questions/1845493/should-i-make-a-daterange-object – Honeyboy Wilson May 02 '18 at 02:16
  • 1
    What is `TotalDates`? That's not a property of a TimeSpan. Do you mean `TotalDays`? – Rufus L May 02 '18 at 02:18
  • 2
    How is the solution you've shown not efficient? What is the problem you're encountering? – Rufus L May 02 '18 at 02:21
  • 1
    Are you looking for something like this: `var d = Enumerable.Range(0, int.MaxValue).Select(x => dtp1.Value.Date.AddDays(x)).TakeWhile(x => x <= dtp2.Value.Date).ToArray();`? If so, why? – Enigmativity May 02 '18 at 02:25
  • 2
    `var d = Enumerable.Range(0, (int) (dtp2.Value - dtp1.Value).TotalDays + 1).Select(i => dtp1.Value.AddDays(i)).ToArray();` – Rufus L May 02 '18 at 02:30
  • Will the last two statements better then for loop!? Performance-wise!? Besides, it's currently out of my league! I need to go research how and why things are such used! Thank you very much for you guys' help!!! – Pikachu620 May 02 '18 at 03:45

1 Answers1

3

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

  • Can you elaborate why lists over arrays? List is backed by an array internally (and one that can grow if resizing is needed, causing copying). – Zer0 May 02 '18 at 02:38
  • https://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which This answer led me to recommend the lists. Really the management that can be given to a list seems to me much greater – Juan Sebastián Vargas May 02 '18 at 02:44