Filter DateTime From DataTable In C#

Introduction

DataTable
– It is a class which represents in-memory data. It stores rows and columns of data. We can add, select and iterate over data. It is available in System.Data namespace.

Suppose you have one DataTable with columns ID, Name, DOB and it holds 5000 rows. But you need those rows which DOB is before ‘01/30/1990’ then you need to implement some kind of filtration to achieve the same. One can think that he/she can manually loop over 5000 records and check the DOB. But it may create performance overhead to your application. So DataTable provides Select command which helps to filter data from DataTable by passing FilterExpression. Select() executes FilterExpression and returns DataRow array.
 
Syntax: DataTableObj.Select(FilterExpression)
 
DataTableObj is DataTable Object.
Select is method in DataTable which will filter DataRows.
FilterExpression is condition you want execute(like DOB in above example)
 
Let’s implement DataTable Filtration:
 
Step 1: In the following example we are creating a Demo DataTable having one column and adding 3 rows to it. Here is the code:
  1. // Create two DataTable instances.  
  2. DataTable table1 = new DataTable("patients");  
  3. table1.Columns.Add("OptionNumber");  
  4.   
  5. DataRow dtrow1 = table1.NewRow();    // Create New Row  
  6. dtrow1["OptionNumber"] = DateTime.Now.AddMinutes(-5);  
  7. table1.Rows.Add(dtrow1);  
  8.   
  9. DataRow dtrow2 = table1.NewRow();    // Create New Row  
  10. dtrow2["OptionNumber"] = DateTime.Now.AddMinutes(-10);  
  11. table1.Rows.Add(dtrow2);  
  12.   
  13. DataRow dtrow3 = table1.NewRow();    // Create New Row  
  14. dtrow3["OptionNumber"] = DateTime.Now.AddMinutes(2);  
  15. table1.Rows.Add(dtrow3);  
Step 2: Here we are adding Filtration to get all rows which are greater than today's date time. In expression we need to add "#" before and after date string otherwise it will throw you missing operand exception. Here is the code: 
  1. string expression;  
  2. expression = string.Format("OptionNumber > #{0}#",   
  3.              DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"));  
  4.   
  5. DataRow[] foundRows;  
  6.   
  7. // Use the Select method to find all rows matching the filter.  
  8. foundRows = table1.Select(expression);  
  9.   
  10. // Print column 0 of each returned row.  
  11. for (int i = 0; i < foundRows.Length; i++)  
  12. {  
  13.     Console.WriteLine(foundRows[i][0]);  
  14. }  
See the result in Figure 1 it returns only one row after filtration but we added 3 rows to DataTable (Step 1). 

Output
 
Figure 1: Result of filtration in DataTable
 
Hope it helps you how to implement DateTime filtration in DataTable. 
Ebook Download
View all
Learn
View all