DataView.RowFilter Vs DataTable.Select() vs DataTable.Rows.Find()

前端 未结 2 1263
故里飘歌
故里飘歌 2020-12-12 15:31

Considering the code below:

Dataview someView = new DataView(sometable)
someView.RowFilter = someFilter;

if(someView.count > 0) {  …. }

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 15:45

    Thomashaid's post sums it up nicely:

    • DataView.RowFilter is for binding.
    • DataTable.Rows.Find is for searching by primary key only.
    • DataTable.Select is for searching by multiple columns and also for specifying an order.

    Avoid creating many DataViews in a loop and using their RowFilters to search for records. This will drastically reduce performance.

    I wanted to add that DataTable.Select can take advantage of indexes. You can create an index on a DataTable by creating a DataView and specifying a sort order:

    DataView dv = new DataView(dt);
    dv.Sort = "Col1, Col2";
    

    Then, when you call DataTable.Select(), it can use this index when running the query. We have used this technique to seriously improve performance in places where we use the same query many, many times. (Note that this was before Linq existed.)

    The trick is to define the sort order correctly for the Select statement. So if your query is "Col1 = 1 and Col2 = 4", then you'll want "Col1, Col2" like in the example above.

    Note that the index creation may depend on the actual calls to create the DataView. We had to use the new DataView(DataTable dt) constructor, and then specify the Sort property in a separate step. The behavior may change slightly with different .NET versions.

提交回复
热议问题