Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve specific days of the week within a given range from Linq?

Tags:

c#

Is it possible given a date range to pull out specific days of the week and display their dates?

So, if my date range is from 08/17/2012 to 09/17/2012 is it possible, using linq to pull out say, all of the Thursdays and Tuesdays?

like image 954
DDiVita Avatar asked Jul 24 '12 13:07

DDiVita


2 Answers

You can determine the number of days between the dates, then generate all the dates and filter on the days of the week you're interested in.

var start = DateTime.Parse("08/17/2012");
var end = DateTime.Parse("09/17/2012");
int numberOfDays = end.Subtract(start).Days + 1;
var daysOfWeek = new[] { DayOfWeek.Tuesday, DayOfWeek.Thursday };

var dates = Enumerable.Range(0, numberOfDays)
                      .Select(i => start.AddDays(i))
                      .Where(d => daysOfWeek.Contains(d.DayOfWeek));
like image 97
Ahmad Mageed Avatar answered Sep 22 '22 00:09

Ahmad Mageed


var start = new DateTime(2012, 8, 17);
var end = new DateTime(2012, 9, 17);

var daysToChoose = new DayOfWeek[] { DayOfWeek.Thursday, DayOfWeek.Tuesday };

var dates = Enumerable.Range(0, (int)(end - start).TotalDays + 1)
                        .Select(d => start.AddDays(d))
                        .Where(d => daysToChoose.Contains(d.DayOfWeek));
like image 34
digEmAll Avatar answered Sep 21 '22 00:09

digEmAll