Export (0) Print
Expand All

DataTable.Select Method (String, String, DataViewRowState)

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

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

public DataRow[] Select(
	string filterExpression,
	string sort,
	DataViewRowState recordStates


Type: System.String

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

Type: System.String

A string specifying the column and sort direction.

Type: System.Data.DataViewRowState

One of the DataViewRowState values.

Return Value

Type: System.Data.DataRow[]
An array of DataRow objects.

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 and record state to return an array of DataRow objects.

    private static void GetRowsByFilter()
        DataTable customerTable = new DataTable("Customers");
        // Add columns
        customerTable.Columns.Add("id", typeof(int));
        customerTable.Columns.Add("name", typeof(string));

        // Set PrimaryKey
        customerTable.Columns[ "id" ].Unique = true;
        customerTable.PrimaryKey = new DataColumn[] 
            { customerTable.Columns["id"] };

        // Add ten rows 
        for(int id=1; id<=10; id++)
                new object[] { id, string.Format("customer{0}", id) });

        // Add another ten rows 
        for(int id=11; id<=20; id++)
                new object[] { id, string.Format("customer{0}", id) });

        string expression;
        string sortOrder;
        expression = "id > 5";
        // Sort descending by column named CompanyName.
        sortOrder = "name DESC";
        // Use the Select method to find all rows matching the filter.
        DataRow[] foundRows = 
            customerTable.Select(expression, sortOrder, 
        PrintRows(foundRows, "filtered rows");

        foundRows = customerTable.Select();
        PrintRows(foundRows, "all rows");

    private static void PrintRows(DataRow[] rows, string label)
        Console.WriteLine("\n{0}", label);
        if(rows.Length <= 0)
            Console.WriteLine("no rows found");
        foreach(DataRow row in rows)
            foreach(DataColumn column in row.Table.Columns)
                Console.Write("\table {0}", row[column]);

.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
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft