This is a C# 4.0 WinForms app.
I'm trying to pull all the Monday dates in a given month (the fully spelled out Month name and day), and the days in all the Sundays. Then, using StreamWriter, write these to a text file.
I found the following code suggestion on enumerating through a month, on StackOverFlow below.
How to get every monday of given month?
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
And then you can call with LINQ like so:
var mondays = AllDatesInMonth(2017, 7).Where(i => i.DayOfWeek == DayOfWeek.Monday);
I modified the suggestion to also pull the Sunday dates. I'm testing this, in order to make it part of a larger application.
This is what I've come up with so far, as shown below.
private void btnTestDayOWeek_Click(object sender, EventArgs e)
{
int curYear = DateTime.Now.Year;
int month = DateTime.Now.Month;
string outputFile = @"C:\dates2Compare.txt";
List<string> mondayList = new List<string>();
List<string> sundayList = new List<string>();
using (StreamWriter sw = new StreamWriter(outputFile))
{
var mondays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Monday);
var sundays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Sunday);
foreach (DateTime Monday in mondays)
{
mondayList.Add(Monday.ToString("MMMM d"));
}
foreach (DateTime Sunday in sundays)
{
sundayList.Add(Sunday.ToString("-d"));
}
var dayList = mondayList.Concat(sundayList);//attempt to join these 2-Lists
foreach (string dt in dayList)
{
sw.WriteLine(dt);
}
}
}
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
I need to join the Monday to Sunday dates, like this, i.e.
March 1-7
March 8-14
But this is what I'm receiving so far.
March 1
March 8
March 15
March 22
March 29
-7
-14
-21
-28
Can someone suggest how to modify my code so that, the text file that is written to, correctly displays the Monday date with a "-" after it and then the Sunday date?