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:
-
- DataTable table1 = new DataTable("patients");
- table1.Columns.Add("OptionNumber");
-
- DataRow dtrow1 = table1.NewRow();
- dtrow1["OptionNumber"] = DateTime.Now.AddMinutes(-5);
- table1.Rows.Add(dtrow1);
-
- DataRow dtrow2 = table1.NewRow();
- dtrow2["OptionNumber"] = DateTime.Now.AddMinutes(-10);
- table1.Rows.Add(dtrow2);
-
- DataRow dtrow3 = table1.NewRow();
- dtrow3["OptionNumber"] = DateTime.Now.AddMinutes(2);
- 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:
- string expression;
- expression = string.Format("OptionNumber > #{0}#",
- DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"));
-
- DataRow[] foundRows;
-
-
- foundRows = table1.Select(expression);
-
-
- for (int i = 0; i < foundRows.Length; i++)
- {
- Console.WriteLine(foundRows[i][0]);
- }
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.