Sorting and Filtering in Data Table

Sorting and Filtering are two common requirements we need in every application because now a days data is becoming large and huge. To manipulate data we need sorting and filtering. Sorting and Filtering is used everywhere, not just in applications. Whenever we talk about data we need sorting and filtering because it gives an easy way in calculation and manipulation. So in this article I will cover sorting and filtering in a DataTable. 

A DataTable is commonly used in .Net applications and if we can apply sorting in a data table directly then we can bind it to a grid or any other control.

1. I have created a small Data table in my WPF application and created 2 columns in it and added some rows.

Data table in my WPF

2. You can see the rows that I have added.

Data table

3. Now I want to apply sorting in my table so there are two ways I am doing that. One is we can sort it using a DataView and the other is using a Select Statement.

4. I have added these two lines of code:


5. It's organizing the table in sorted order w.r.t. ColA.

working the table

6. Now I need to sort based on two columns and now I am using a select statement and again two lines of code.

data row code

7. The table is sorted based on both columns and see the output .The last two rows are interchanged because of ColB sorting.

see output

8. In the dt.Select statement there is the first empty string for a filter expression. If you want to filter the table you can provide filterExpression like “ColA=5”. It will return one row in this table.

Similar Articles