Introduction
While working on a project, I came across a scenario where I have to loop through each day of a calendar year. In this article, we will try to loop between date ranges. We will use IEnumerable interface and the "yield" keyword in C# to achieve this.
IEnumerable Interface
IEnumerable is the base interface for all non-generic collections that can be enumerated.
Namespace: System.Collection
Yield Keyword
With the help of "yield" keyword, we can read an element from the loop, return to the calling code, go back again to the same point from where it left the loop, and continue processing the loop for other records.
Now, let’s begin.
Create a function like below.
- public IEnumerable < DateTime > EachCalendarDay(DateTime startDate, DateTime endDate) {
- for (var date = startDate.Date; date.Date <= endDate.Date; date = date.AddDays(1)) yield
- return date;
- }
Consume the above function.
- DateTime StartDate = Convert.ToDateTime("15-08-2017");
- DateTime EndDate = Convert.ToDateTime("20-08-2017");
- foreach(DateTime day in EachCalendarDay(StartDate, EndDate)) {
- Console.WriteLine("Date is : " + day.ToString("dd-MM-yyyy"));
- }
Complete Program
- class Program {
- static void Main(string[] args) {
- DateTime StartDate = Convert.ToDateTime("15-08-2017");
- DateTime EndDate = Convert.ToDateTime("20-08-2017");
- foreach(DateTime day in EachCalendarDay(StartDate, EndDate)) {
- Console.WriteLine("Date is : " + day.ToString("dd-MM-yyyy"));
- }
- }
- public static IEnumerable < DateTime > EachCalendarDay(DateTime startDate, DateTime endDate) {
- for (var date = startDate.Date; date.Date <= endDate.Date; date = date.AddDays(1)) yield
- return date;
- }
- }
Summary
In this blog, we learned how we can iterate between date ranges.
I hope this will be helpful to some extent. Your thoughts and comments are always welcome.