Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

DataTable.Select Method (String, String)

Gets an array of all DataRow objects that match the filter criteria, in the specified sort order.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)

public DataRow[] Select(
	string filterExpression,
	string sort
)

Parameters

filterExpression
Type: System.String

The criteria to use to filter the rows. For examples on how to filter rows, see DataView RowFilter Syntax [C#].

sort
Type: System.String

A string specifying the column and sort direction.

Return Value

Type: System.Data.DataRow[]
An array of DataRow objects matching the filter expression.

To form the filterExpression argument, use the same rules for creating the DataColumn class's Expression property value. The Sort argument also uses the same rules for creating class's Expression strings.

If the column on the filter contains a null value, it will not be part of the result.

The following example uses a filter expression to return an array of DataRow objects.

using System;
using System.Data;

public class A {  

   public static void Main() {      
      DataTable table = new DataTable("Orders");
      table.Columns.Add("OrderID", typeof(Int32));
      table.Columns.Add("OrderQuantity", typeof(Int32));
      table.Columns.Add("CompanyName", typeof(string));      
      table.Columns.Add("Date", typeof(DateTime));

      DataRow newRow = table.NewRow();
      newRow["OrderID"] = 1;
      newRow["OrderQuantity"] = 3;
      newRow["CompanyName"] = "NewCompanyName";
      newRow["Date"] = "1979, 1, 31";

      // Add the row to the rows collection.
      table.Rows.Add(newRow);

      DataRow newRow2 = table.NewRow();
      newRow2["OrderID"] = 2;
      newRow2["OrderQuantity"] = 2;
      newRow2["CompanyName"] = "NewCompanyName1";
      table.Rows.Add(newRow2);

      DataRow newRow3 = table.NewRow();
      newRow3["OrderID"] = 3;
      newRow3["OrderQuantity"] = 2;
      newRow3["CompanyName"] = "NewCompanyName2";
      table.Rows.Add(newRow3);

      // Presuming the DataTable has a column named Date. 
      string expression = "Date = '1/31/1979' or OrderID = 2";
      // string expression = "OrderQuantity = 2 and OrderID = 2";

      // Sort descending by column named CompanyName. 
      string sortOrder = "CompanyName ASC";
      DataRow[] foundRows;

      // Use the Select method to find all rows matching the filter.
      foundRows = table.Select(expression, sortOrder);

      // Print column 0 of each returned row. 
      for (int i = 0; i < foundRows.Length; i++)
         Console.WriteLine(foundRows[i][2]);
   }
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0
Show:
© 2015 Microsoft