Grouping data in a datatable based on data in a column
I have a datatable as below
**Name** **Department**
abc dept 1
def dept 2
ghi dept 1
jkl dept 1
mno dept 2
pqr dept 1
I need to group the data in the datatable such that all names having Department as dept1 comes togather and then all names having Department dept2 comes next (as shown below) and save it in another datatable.
**Name** **Department**
abc dept 1
ghi dept 1
jkl dept 1
pqr dept 1
def dept 2
mno 开发者_StackOverflow社区dept 2
You can fetch the data in the ordered way that you want by using the statement below:
SELECT * FROM YourTable
ORDER BY Department ASC, Name ASC
This will sort the results with Department as the primary sorting key, and Name as the secondary. Both columns are sorted in ASC = ascending order (which is also the default sort order). If you have added indexes to these two columns, the sorted results will be retrieved as quickly as any other query on the table. I don't understand why you would want to save this sorted result in another table..
EDIT
If you already have the data unsorted in a DataTable
you can still retrieve a sorted version without duplication by using the following code
yourDataTable.DefaultView.Sort = "Department ASC, Name ASC";
For binding this Data sorted, you dont need a new Table. Just use the Select statement from your Datatable.
Datatable Select method
精彩评论