Background

There is often a need to get a List/Datatable between two supplied dates.

Two days ago I needed to make a join between two Datatables so I thought I must share it among developers.

A scenario is that there is a table named user with a registration date. What I need to do is to create a report that will display the record for the users registered every month of this year. What I did was I fetched the data from the database that is like the following.

Table in my database

Now, I need to display a report for the users registered between 01/08/2013 and 01/03/2014.

So, I created a Datatable for all the months between those dates.

For this given below.

Just created a class.
  1. public class BhanuHelper
  2. {
  3. public static Array GetMonths(DateTime date1, DateTime date2)
  4. {
  5. //Note - You may change the format of date as required.
  6. return GetDates(date1, date2).Select(x => x.ToString("MMMM yyyy")).ToArray();
  7. }
  8. public static IEnumerable<DateTime> GetDates(DateTime date1, DateTime date2)
  9. {
  10. while (date1 <= date2)
  11. {
  12. yield return date1;
  13. date1 = date1.AddMonths(1);
  14. }
  15. if (date1 > date2 && date1.Month==date2.Month)
  16. {
  17. // Include the last month
  18. yield return date1;
  19. }
  20. }
  21. public static DataTable ToDataTable<T>( IList<T> data)
  22. {
  23. PropertyDescriptorCollection props =
  24. TypeDescriptor.GetProperties(typeof(T));
  25. DataTable table = new DataTable();
  26. for (int i = 0; i < props.Count; i++)
  27. {
  28. PropertyDescriptor prop = props[i];
  29. table.Columns.Add(prop.Name, prop.PropertyType);
  30. }
  31. object[] values = new object[props.Count];
  32. foreach (T item in data)
  33. {
  34. for (int i = 0; i < values.Length; i++)
  35. {
  36. values[i] = props[i].GetValue(item);
  37. }
  38. table.Rows.Add(values);
  39. }
  40. return table;
  41. }
  42. }
Implementation of above class
  1. BhanuHelper.ToDataTable(BhanuHelper.GetMonths(Convert.ToDateTime("First date string"),Convert.ToDateTime("second date string")));
And the output will be like below:I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.