C # sort table by 2 columns

I have a two-column table containing the columns CustomerName and Age. I have all the data in a DataTable. I want to sort it in descending order by Age, and then each age group is sorted by name. Thus, all people aged 30 years will be sorted alphabetically and will be between the lists of people aged 29 to 31 years.

I have:

string selectStatement = "Age";
string sortStatement = "Age DESC"

var rows = table.Select(selectStatement, sortStatement);

It should be sorted by age. I did not understand how to sort each age group alphabetically, but the above throws an exception:

The age filter expression is not evaluated in a boolean expression.

+5
source share
7 answers

@adrift. ( boolean) . , , Select . - , 0 < 1. : "Age Desc, Name".

, DataView. :

var dt = new DataTable(); // your data.
var view = new DataView(dt);
view.Sort = "Age desc, Name asc";

.. . foreach .

foreach (DataRowView dr in view)
{
    //do what you like
}
+3

Select , .

+1

- .

linq :

var rows = table.AsEnumerable().OrderByDescending(row => row.Field<int>("Age")).
                                ThenBy(row => row.Field<string>("Name"));
+1

, DataTable.Select , select SQL Select.

:

table.DefaultView.Sort = "Age DESC";
0

selectStatement . .

, selectExpression

string selectStatement = "Age > 0"; //if all people required
0

null, , , , ( - asc). , DataTables , LINQ.

0

DataView oDataSet; oDataSet.Tables [0].DefaultView.Sort = "Column1 ASC";

0

All Articles