HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Get remaining days in date range

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
remainingrangedategetdays

Problem

I wonder if there are some possible ways to simplify my code.

startDate = '04/02/2014'
endDate = '04/06/2014'

mondayTag = 0
tuesdayTag = 0
wednesdayTag = 1
thursdayTag = 0
fridayTag = 1
saturdayTag = 0
sundayTag = 0

public int GetRemainingDays(DateTime startDate, DateTime endDate, bool mondayTag, bool tuesdayTag, bool wednesdayTag, bool thursdayTag, bool fridayTag, bool saturdayTag, bool sundayTag)
{
    int i = 0;
    for (DateTime day = startDate.AddDays(1); day.Date  0 ? i : 0;
}

Solution

Using System.Linq library the method can be rewritten like this:

public static int GetRemainingDays(DateTime startDate, DateTime endDate, ISet includedDays)
{
    return Enumerable.Range(0, Int32.MaxValue)
        .Select(n => startDate.AddDays(n+1))
        .TakeWhile(date => date  includedDays.Contains(date.DayOfWeek));
}


Which can then be more easily called like this:

GetRemainingDays(startDate, endDate, 
    new HashSet{DayOfWeek.Wednesday, DayOfWeek.Friday});


Note: You should test this (and the original version) against off-by-one errors.

Code Snippets

public static int GetRemainingDays(DateTime startDate, DateTime endDate, ISet<DayOfWeek> includedDays)
{
    return Enumerable.Range(0, Int32.MaxValue)
        .Select(n => startDate.AddDays(n+1))
        .TakeWhile(date => date <= endDate)
        .Count(date => includedDays.Contains(date.DayOfWeek));
}
GetRemainingDays(startDate, endDate, 
    new HashSet<DayOfWeek>{DayOfWeek.Wednesday, DayOfWeek.Friday});

Context

StackExchange Code Review Q#46010, answer score: 4

Revisions (0)

No revisions yet.