
The DataTable has a Select method. This method receives a string expression that specifies what rows you want to select. Select makes DataTables act more like small databases.
This C# article shows how to use Select on a DataTable instance.
The first part of this program simply adds five DataRows to a DataTable with two DataColumns. Each Player is added with a Size and Sex field. Next, we invoke Select with the parameter "Size >= 230 and Sex = 'm'". This results in an array of DataRow instances where every Player has those matching characteristics.
Program that uses DataTable Select method [C#]
using System;
using System.Data;
class Program
{
static void Main()
{
// Create a table of five different people.
// ... Store their size and sex.
DataTable table = new DataTable("Players");
table.Columns.Add(new DataColumn("Size", typeof(int)));
table.Columns.Add(new DataColumn("Sex", typeof(char)));
table.Rows.Add(100, 'f');
table.Rows.Add(235, 'f');
table.Rows.Add(250, 'm');
table.Rows.Add(310, 'm');
table.Rows.Add(150, 'm');
// Search for people above a certain size.
// ... Require certain sex.
DataRow[] result = table.Select("Size >= 230 AND Sex = 'm'");
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
}
Output
250, m
310, m
The syntax to the Select method is somewhat tricky. It is SQL-style syntax but because it is inside a string literal, you sometimes need to escape quotation marks. Some values, like characters, may need to be quoted. The AND and OR operators can be used as in SQL. There is an example of Select with DateTime filters on MSDN.
MSDN referenceThe Select method receives a predicate expression in the SQL special form and returns an array of DataRow instances. If you specify an invalid column name, it will throw an exception. Select provides another way of filtering DataTables, separate from imperative testing with if-statements and loops.
Data