Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some ways to get a list of DateTime.Now.AddDays(0..7) dynamically?

The most efficient and typical solution that I could think of is:

var dates = new DateTime[7];
for (int i = 0; i < 7; i++)
  dates[i] = DateTime.Now.AddDays(i);

This will return me seven (7) dates in an array, which is the result I want. I think ruby can do something like this, simply by specifying dots but I can't recall.

However, is there a more efficient approach? Or is there any way to implement this using linq (possibly via the Aggregate method?), if there is, even if it is not the most efficient solution I would be curious to see.

Ideally it would not require you to re-declare any object instance for the amount of "times" you need though, and allow you to specify DateTime.Now just once and the number of items in the array/list you want just once.

Thanks

like image 494
GONeale Avatar asked Apr 20 '11 06:04

GONeale


1 Answers

I would use Enumerable.Range, which is very handy when it comes to generating sequences of data:

var now = DateTime.Now;
var dates = Enumerable.Range(0, 7).Select(n => now.AddDays(n)).ToArray();
like image 191
Fredrik Mörk Avatar answered Oct 11 '22 03:10

Fredrik Mörk