Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why DataTable.Select sorts the data by default

I have a dataset with the following data

Name          Value    Percent
0-3 months    0        0
3-12 months   0        0
1-5 years     1234.12  28
5-10 years    13144.11 68
10-15 years   0        0
Over 15 years 1233.44  14
Other Income  2245.12  

when I try

foreach (DataRow dr in dsMaturity.Tables[0].Select("name not like 'Other%'"))
{
    TotalValue += double.Parse(dr["Value"].ToString());
}

Edit: Actually, similar to the above code. I am using the similar loop to add the data to display bucket which eventually writes to the chart.

foreach (DataRow dr in dsMaturity.Tables[0].Rows)
{
    //Add to the display bucket
}

I get the data sorted like:

0-3 months
10-15 years
1-5 years
3-12 months
5-10 years
Over 15 years

Why? How can I have the data unsorted? This is critical since I show the data in my chart object. Am I missing something here?

like image 985
Sri Reddy Avatar asked Jun 13 '11 18:06

Sri Reddy


People also ask

How do I change the default sort in DataTable?

Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.

What is sorting table data?

Sorting is the process of arranging data into meaningful order so that you can analyze it more effectively. For example, you might want to order sales data by calendar month so that you can produce a graph of sales performance. You can use Discoverer to sort data as follows: sort text data into alphabetical order.

Can we sort DataTable in C#?

Import each row from original table to clone table. Commit the changes in clone table. Create a DataView on clone table. Specify the sort column and sort order for the DataView.


2 Answers

dataTable.Select(filterExpression) does not guarantee a sort order. As the documentation says, you should use one fo the other overloads to supply your sort order.

In our experiment, the result set was ordered by the filter column, but I would not trust later versions of .NET to behave the same way (as it's not documented that way).

like image 150
hangy Avatar answered Sep 27 '22 23:09

hangy


I had this problem too, the answer is:

dataTable.AsEnumerable();

instead of

dataTable.Select();
like image 31
Siamak Ferdos Avatar answered Sep 27 '22 22:09

Siamak Ferdos