user673453
user673453

Reputation: 167

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             dept 2

Upvotes: 0

Views: 418

Answers (2)

Simen S
Simen S

Reputation: 3205

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";

Upvotes: 3

SwissGuy
SwissGuy

Reputation: 565

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

Datatable Select method

Upvotes: 0

Related Questions