C# DateTable.Select - DateTime comparison filter

Dear all,

  I got an email from my colleague today. Basically he wanted to filter a DataTable based on a date range. So I decided to help him out. I am using a Console application to demonstrate the solution, however you can do this in asp.net as well. Same stuff :)   

  One thing to take note, I will recommend you to use foreach to loop through the records. First why foreach? Well if you are not sure how many records that you are getting back from database, use foreach. If you know how many, then use for loop. Basically a lot of people say that it is not possible to do this for this scenario:

  foreach (DataRow dRow in dt.Rows)

  So they came into conclusion that foreach were not an option and recommended as below:

  DataRow[] dRow;

  dRow = dt.Select(filter);

  // do your processing here

  However you can do this instead:

  foreach (DataRow dRow in dt.Select(filter))

  Easy right?

   Below is a sample code that is functional. Try it and you will see J

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            // Accepts Input

            string dateFrom = Console.ReadLine();

            string dateTo = Console.ReadLine();

            DateTime daDateFrom = DateTime.Parse(dateFrom);

            DateTime daDateTo = DateTime.Parse(dateTo);

            DataTable dt = GetFromDatabase();

            string filter = "DateFrom > '" + daDateFrom + "' AND DateTo <= '" + daDateTo + "'";

            // It is not necessary to create DataRow[] array

            // Use foreach as it is much cleaner

            foreach (DataRow dr in dt.Select(sToFiler))

            {

                Console.WriteLine(dr["Name"].ToString());

            }

        }

        private static DataTable GetPreviousEntry()

        {

            DataTable dTable = new DataTable("Table1");

            dTable.Columns.Add("Name", typeof(string));

            dTable.Columns.Add("DateFrom", typeof(DateTime));

            dTable.Columns.Add("DateTo", typeof(DateTime));

            dTable.Rows.Add("Chua Wen Ching", "03/28/2007", "04/01/2007");

            dTable.Rows.Add("Nazir", "1/1/2005", "04/01/2007");

            dTable.Rows.Add("Mahzan", "1/1/1999", "04/01/2007");

            return dTable;

        }

    }

}

Published Thursday, March 29, 2007 10:08 AM by chuawenching
Filed under: ,

Comments

# Seth

Monday, August 04, 2008 3:23 PM by Collin

f87d44805d4b42bc75969d74a6047d17

<a href="njdokj.info/.../f87d44805d4b42bc75969d74a6047d17">">njdokj.info/.../f87d44805d4b42bc75969d74a6047d17"> njdokj.info/.../f87d44805d4b42bc75969d74a6047d17 </a>

njdokj.info/.../f87d44805d4b42bc75969d74a6047d17

[url]njdokj.info/.../f87d44805d4b42bc75969d74a6047d17[url]