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
)

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.

recordStates
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++)
    {
        customerTable.Rows.Add(
            new object[] { id, string.Format("customer{0}", id) });
    }
    customerTable.AcceptChanges();

    // Add another ten rows
    for(int id=11; id<=20; id++)
    {
        customerTable.Rows.Add(
            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, 
        DataViewRowState.Added);

    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");
        return;
    }
    foreach(DataRow row in rows)
    {
        foreach(DataColumn column in row.Table.Columns)
        {
            Console.Write("\table {0}", row[column]);
        }
        Console.WriteLine();
    }
}

.NET Framework
Available since 1.1
Return to top
Show: