I ultimately want to get every date for the current year in a List.
I have the following which gives me all dates for a given month..
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
public static void Main(String[] args)
{
List<DateTime> ldtDates = new List<DateTime>();
Random rnd = new Random();
int intCurrentYear = DateTime.Now.Year;
int intCurrentMonth = DateTime.Now.Month;
List<DateTime> DatesThisMonth =
Enumerable.Range(1, DateTime.DaysInMonth(intCurrentYear, intCurrentMonth))
.Select(i => new DateTime(intCurrentYear, intCurrentMonth, i))
.ToList();
foreach (var q in DatesThisMonth)
{
Console.WriteLine(q);
}
Console.WriteLine("Press <enter> to continue");
Console.ReadLine();
}
}
This works for the month, however I want to wrap a Range(1,12) around this code like this:
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
public static void Main(String[] args)
{
List<DateTime> ldtDates = new List<DateTime>();
Random rnd = new Random();
int intCurrentYear = DateTime.Now.Year;
int intCurrentMonth = DateTime.Now.Month;
var DatesThisYesr =
Enumerable.Range(1, 12).Select(y=>
Enumerable.Range(1, DateTime.DaysInMonth(intCurrentYear, y))
.Select(i => new DateTime(intCurrentYear, intCurrentMonth, i))
).ToList();
foreach (var q in DatesThisYesr)
{
Console.WriteLine(q);
}
Console.WriteLine("Press <enter> to continue");
Console.ReadLine();
}
}
Here is what my output looks like:
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Int32,System.DateT
ime]
Press <enter> to continue
I could use a For loop, however it should be possible to do this via Linq.
Thanks,
Use SelectMany
like this:
var DatesThisYesr =
Enumerable.Range(1, 12)
.SelectMany(month =>
Enumerable.Range(1, DateTime.DaysInMonth(intCurrentYear, month))
.Select(day => new DateTime(intCurrentYear, month, day)))
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With