Saturday, September 18, 2010

Enumerable Select Magic in C#

I'd always wanted to toy with the "Select" extension method that lives in the System.Linq namespace, and today I found a great opportunity to use it.

I had to calculate the number of working days between two dates (e.g. no weekends), and to do this I used a mix of the Range method on the Enumerable class and the select method, plus a list of the weekdays. The result is below.

public int WorkingDays(DateTime startDate, DateTime endDate)
{
int totalDays = endDate.Subtract(startDate).Days + 1;

List<DayOfWeek> businessDays = new List<DayOfWeek>()
{ System.DayOfWeek.Monday, System.DayOfWeek.Tuesday, System.DayOfWeek.Wednesday,
System.DayOfWeek.Thursday, System.DayOfWeek.Friday };

return Enumerable.Range(0, totalDays)
.Select( d => startDate.AddDays(d))
.Where( wd => businessDays.Contains(wd.DayOfWeek)).Count();

}

 

Anyway, I think it's a great basic example of how to use the select method, so I thought I'd share it.