0

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             dept 2
1
  • @Daniel I have retrieved the data from the database and saved it in the datatable. I need to manipulate the data in the datatable so that the output will be as above. Commented Apr 6, 2011 at 9:22

2 Answers 2

3

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";
Sign up to request clarification or add additional context in comments.

4 Comments

I have retrieved the data from the database and saved it in the datatable. I need to manipulate the data in the datatable so that the output will be as above.
Have you retrieved it with the query that I specified above? If so, then it will be correctly ordered. The only difference that I can observe between your two lists of rows is that the second one is sorted according to Department and Name.
I have to use a simple select statement to retrieve the data from the database. Also the datasource that I use to retrieve the data can be an xml file in which case sql query cannot be used. Is there any other way to manipulate the data in the datatable so that I get the second list as the output.
Thanks for your help. Its working. It doesn't seem to work with the datatable but it worked when dataview was used.
0

For binding this Data sorted, you dont need a new Table. Just use the Select statement from your Datatable.

Datatable Select method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.