使用 DataView 進行排序 (LINQ to DataSet)Sorting with DataView (LINQ to DataSet)

根據特定準則來排序資料,然後透過 UI 控制項呈現資料給用戶端的功能是資料繫結的重要層面。The ability to sort data based on specific criteria and then present the data to a client through a UI control is an important aspect of data binding. DataView 提供了許多方式來排序資料並傳回依據特定排序準則所排序的資料列。DataView provides several ways to sort data and return data rows ordered by specific ordering criteria. 除了以字串為基礎的排序功能之外, DataView也可讓您Language-Integrated Query (LINQ)Language-Integrated Query (LINQ)將運算式用於排序準則。In addition to its string-based sorting capabilities, DataView also enables you to use Language-Integrated Query (LINQ)Language-Integrated Query (LINQ) expressions for the sorting criteria. LINQLINQ運算式除了以字串為基礎的排序,還允許更複雜且功能更強大的排序作業。expressions allow for much more complex and powerful sorting operations than string-based sorting. 本主題將說明兩種使用 DataView 進行排序的方法。This topic describes both approaches to sorting using DataView.

從含有排序資訊的查詢中建立 DataViewCreating DataView from a Query with Sorting Information

您可以從 LINQ to DataSet 查詢建立物件。DataViewA DataView object can be created from a LINQ to DataSet query. 如果該查詢包含OrderBy、、 OrderByDescending ThenByThenByDescending子句,這些子句中的運算式DataView會用來做為排序中資料的基礎。If that query contains an OrderBy, OrderByDescending, ThenBy, or ThenByDescending clause the expressions in these clauses are used as the basis for sorting the data in the DataView. 例如,如果查詢包含Order By…Then By…子句,則產生DataView的會依據指定的兩個數據行來排序資料。For example, if the query contains the Order By…and Then By… clauses, the resulting DataView would order the data by both columns specified.

以運算式為基礎的排序會比較簡單的以字串為基礎的排序提供功能更強大且更複雜的排序。Expression-based sorting offers more powerful and complex sorting than the simpler string-based sorting. 請注意,以字串為基礎的排序和以運算式為基礎的排序會互斥 (Mutually Exclusive)。Note that string-based and expression-based sorting are mutually exclusive. 如果您從查詢中建立 Sort 之後才設定以字串為基礎的 DataView,就會清除從查詢中推斷的以運算式為基礎的篩選,而且無法加以重設。If the string-based Sort is set after a DataView is created from a query, the expression-based filter inferred from the query is cleared and cannot be reset.

在您建立 DataView 以及修改任何排序或篩選資訊時,系統就會建立 DataView 的索引。The index for a DataView is built both when the DataView is created and when any of the sorting or filtering information is modified. 在建立的 LINQ to DataSet 查詢DataView中提供排序準則,並在稍後不修改排序資訊,以獲得最佳效能。You get the best performance by supplying sorting criteria in the LINQ to DataSet query that the DataView is created from and not modifying the sorting information, later. 如需詳細資訊,請參閱DataView PerformanceFor more information, see DataView Performance.

注意

在大部分清況中,用於排序的運算式不應該具有副作用 (Side Effect) 而且必須具決定性。In most cases, the expressions used for sorting should not have side effects and must be deterministic. 此外,這些運算式不應該包含取決於固定執行次數的任何邏輯,因為排序作業可能會執行任何次數。Also, the expressions should not contain any logic that depends on a set number of executions, because the sorting operations might be executed any number of times.

範例Example

下列範例會查詢 SalesOrderHeader 資料表並依據訂單日期排序傳回的資料列、從該查詢中建立 DataView,然後將 DataView 繫結至 BindingSourceThe following example queries the SalesOrderHeader table and orders the returned rows by the order date; creates a DataView from that query; and binds the DataView to a BindingSource.

DataTable orders = dataSet.Tables["SalesOrderHeader"];

EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
                                         orderby order.Field<DateTime>("OrderDate")
                                         select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;
Dim orders As DataTable = dataSet.Tables("SalesOrderHeader")

Dim query = _
    From order In orders.AsEnumerable() _
    Order By order.Field(Of DateTime)("OrderDate") _
    Select order

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view

範例Example

下列範例會查詢 SalesOrderHeader 資料表並依據總金額排序傳回的資料列、從該查詢中建立 DataView,然後將 DataView 繫結至 BindingSourceThe following example queries the SalesOrderHeader table and orders the returned row by total amount due; creates a DataView from that query; and binds the DataView to a BindingSource.

DataTable orders = dataSet.Tables["SalesOrderHeader"];

EnumerableRowCollection<DataRow> query =
    from order in orders.AsEnumerable()
    orderby order.Field<decimal>("TotalDue")
    select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;

Dim orders As DataTable = dataSet.Tables("SalesOrderHeader")

Dim query = _
    From order In orders.AsEnumerable() _
    Order By order.Field(Of Decimal)("TotalDue") _
    Select order

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view

範例Example

下列範例會查詢 SalesOrderDetail 資料表並先後依據訂單數量和銷售訂單識別碼排序傳回的資料列、從該查詢中建立 DataView,然後將 DataView 繫結至 BindingSourceThe following example queries the SalesOrderDetail table and orders the returned rows by order quantity and then by sales order ID; creates a DataView from that query; and binds the DataView to a BindingSource.

DataTable orders = dataSet.Tables["SalesOrderDetail"];

EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
                                         orderby order.Field<Int16>("OrderQty"), order.Field<int>("SalesOrderID")
                                         select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;

Dim orders As DataTable = dataSet.Tables("SalesOrderDetail")

Dim query = _
    From order In orders.AsEnumerable() _
    Order By order.Field(Of Int16)("OrderQty"), order.Field(Of Integer)("SalesOrderID") _
    Select order

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view

使用以字串為基礎的 Sort 屬性Using the String-Based Sort Property

以字串為基礎的排序功能DataView仍然可與 LINQ to DataSet 搭配使用。The string-based sorting functionality of DataView still works with LINQ to DataSet. 從 LINQ to DataSet 查詢建立之後,您可以Sort使用屬性來DataView設定上的排序。 DataViewAfter a DataView has been created from a LINQ to DataSet query, you can use the Sort property to set the sorting on the DataView.

以字串為基礎的排序和以運算式為基礎的排序功能會互斥。The string-based and expression-based sorting functionality are mutually exclusive. 因此,設定 Sort 屬性將會清除繼承自查詢 (從中建立 DataView) 的以運算式為基礎的排序。Setting the Sort property will clear the expression-based sort inherited from the query that the DataView was created from.

如需以字串為基礎Sort之篩選的詳細資訊,請參閱排序和篩選資料For more information about string-based Sort filtering, see Sorting and Filtering Data.

範例Example

下列範例會從 Contact 資料表中建立 DataView 並按照姓氏的遞減順序排序資料列,然後再按照名字的遞增順序排序資料列:The follow example creates a DataView from the Contact table and sorts the rows by last name in descending order, then first name in ascending order:

DataTable contacts = dataSet.Tables["Contact"];

DataView view = contacts.AsDataView();

view.Sort = "LastName desc, FirstName asc";

bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();
Dim contacts As DataTable = dataSet.Tables("Contact")

Dim view As DataView = contacts.AsDataView()

view.Sort = "LastName desc, FirstName asc"

bindingSource1.DataSource = view
dataGridView1.AutoResizeColumns()

範例Example

下列範例會在 Contact 資料表中查詢是否有以字母 "S" 為開頭的姓氏。The following example queries the Contact table for last names that start with the letter "S". DataView 是從該查詢中建立並繫結至 BindingSource 物件。A DataView is created from that query and bound to a BindingSource object.

DataTable contacts = dataSet.Tables["Contact"];

EnumerableRowCollection<DataRow> query = from contact in contacts.AsEnumerable()
                                         where contact.Field<string>("LastName").StartsWith("S")
                                         select contact;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;

view.Sort = "LastName desc, FirstName asc";
Dim contacts As DataTable = dataSet.Tables("Contact")

Dim query = _
    From contact In contacts.AsEnumerable() _
    Where contact.Field(Of String)("LastName").StartsWith("S") _
    Select contact

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view
view.Sort = "LastName desc, FirstName asc"

清除排序Clearing the Sort

在您已經使用 DataView 屬性來設定排序資訊之後,就可以清除 Sort 上的排序資訊。The sorting information on a DataView can be cleared after it has been set using the Sort property. 目前有兩種方式可以清除 DataView 中的排序資訊:There are two ways to clear the sorting information in DataView:

  • Sort 屬性設定為 nullSet the Sort property to null.

  • Sort 屬性設定為空字串。Set the Sort property to an empty string.

範例Example

下列範例會從查詢中建立 DataView,然後將 Sort 屬性設定為空字串,藉以清除排序:The following example creates a DataView from a query and clears the sorting by setting the Sort property to an empty string:

DataTable orders = dataSet.Tables["SalesOrderHeader"];

EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
                                         orderby order.Field<decimal>("TotalDue") 
                                         select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;

view.Sort = "";
Dim orders As DataTable = dataSet.Tables("SalesOrderHeader")

Dim query = _
    From order In orders.AsEnumerable() _
    Order By order.Field(Of Decimal)("TotalDue") _
    Select order

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view
view.Sort = ""

範例Example

下列範例會從 Contact 資料表中建立 DataView,然後將 Sort 屬性設定為按照姓氏的遞減順序排序。The following example creates a DataView from the Contact table and sets the Sort property to sort by last name in descending order. 然後,系統會將 Sort 屬性設定為 null,藉以清除排序資訊:The sorting information is then cleared by setting the Sort property to null:

DataTable contacts = dataSet.Tables["Contact"];

DataView view = contacts.AsDataView();

view.Sort = "LastName desc";

bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();

// Clear the sort.
view.Sort = null;
Dim contacts As DataTable = dataSet.Tables("Contact")

Dim view As DataView = contacts.AsDataView()
view.Sort = "LastName desc"

bindingSource1.DataSource = view
dataGridView1.AutoResizeColumns()

'Clear the sort.
view.Sort = Nothing

另請參閱See also