1

How can i get the count of working days between two dates in linq. if i am giving like 1/1/2014(LeaveFrom) to 3/1/2014( LeaveTo) , i need to get the answer like '3'. I tried like

NoofDays=  Enumerable.Range(0, 1 + (LA.LeaveTo).Subtract(LA.LeaveFrom).Days)
                                         .Select(offset => (LA.LeaveFrom).AddDays(offset)).Count()
sloth
  • 99,095
  • 21
  • 171
  • 219
Don G
  • 33
  • 2
  • 8
  • possible duplicate of [Calculate the number of business days between two dates?](http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates) – sloth Jun 03 '14 at 11:32
  • I work 7 days a week. Do you mean week days? – Ashigore Jun 03 '14 at 11:49
  • Why cant u use timespan. you will get the result. – Shashank Jun 03 '14 at 12:03
  • `Enumerable.Range(0, 1 + something).Select(whatever).Count()` is just a complicated way of writing `something`. Why do you think you need Linq? – Henrik Jun 03 '14 at 12:16
  • @Henrik Actually, it's the equivalent of `1 + something` (the second parameter of `Range` is the count, not the end value). Presumably 1/1/2014 to 1/1/2014 is considered 1 day of leave, not 0. – nmclean Jun 03 '14 at 14:06

2 Answers2

1

If you're counting every day as a working day, your code already works. Abbreviating things a bit you've got:

Enumerable.Range(0, 1 + (to - from).Days)
    .Select(offset =>(from).AddDays(offset)).Count()

but the Select is redundant as you're only doing a Count afterwards anyway, so:

 Enumerable.Range(0, 1 + (to - from).Days).Count()

but all you're doing here is counting the numbers the Range(int start, int count) function has generated, so all the enumeration was pointless because you've specified this count in the first place, i.e.

1 + (to - from).Days

However, the enumeration would be useful if you wanted to exclude weekends etc. using some to-be-defined function, e.g.

Func<DateTime, bool> isWorkDay = x => 
{
    if(x.DayOfWeek == DayOfWeek.Saturday) return false;
    if(x.DayOfWeek == DayOfWeek.Sunday) return false;
    if(x.Day == 25 && x.Month == 12) return false;
    // etc.
    return true;
};

Enumerable.Range(0, 1 + (to - from).Days)
    .Where(x => isWorkDay(from.AddDays(x))).Count()
stovroz
  • 6,835
  • 2
  • 48
  • 59
0

I would suggest you to use TimeSpan instead. It is easy to get your desired result.

DateTime LeaveFrom= DateTime.ParseExact("01/01/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);    
DateTime LeaveTo = DateTime.ParseExact("03/01/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);    
 TimeSpan dtspan = LeaveTo- LeaveFrom;    
 double diff=  dtspan.TotalDays;
Shashank
  • 401
  • 2
  • 13