Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data table by multiple columns using C#

I have a Datatable with columns named foldername,documentname. Data as below:

FolderName  DocumentName
Folder1     HR[D] Document
Folder1     ___----'
Folder1     Asp_example.pdf
Folder2     SD
Folder3     Heavy_weight
Folder3     Accesorial Services

How to alphabetically sort DocumentName based on FolderName in .Net Framework 2.0.

Solution we tried is below but takes too many time as it contains more than 1200000 records.

int counter=0;

while (counter < searchDT.Rows.Count){
   string FolderName = Convert.ToString(searchDT.Rows[counter]["Folder Name"]);

   string exp = "[Folder Name] like '" + FolderName + "'";

   if (FolderName.Contains("%") || FolderName.Contains("_") || FolderName.Contains("[]") ||      FolderName.Contains("'"))

      exp = "[Folder Name] like '" + EscapeLikeValue(FolderName) + "'";

   string sortExpression = "[Document Name] ASC";

   DataRow[] drfoldername = searchDT.Select(exp, sortExpression);

   foreach (DataRow row in drfoldername)
     drfoldernameDT.ImportRow(row);

   counter += drfoldername.Length;

 }
like image 258
user1931665 Avatar asked Dec 27 '12 09:12

user1931665


People also ask

Is it possible to sort multiple columns in a table?

– There is no limit on the number of columns that can be used to sort a table. Just hold the shift key and keep choosing columns. – This feature is not available for matrices. – To switch the sorting from ascending to descending or vice-versa continue to hold shift and click on the column header again.


2 Answers

DataTable dt = new DataTable();

DataView dv = new DataView(dt);
dv.Sort = "FolderName, DocumentName ASC";

Try that out. It will sort first for FolderName, then DocumentName.

If you need to send that to a component on the screen, you can do the same as you're doing with a DataTable.

like image 67
André Silva Avatar answered Sep 17 '22 15:09

André Silva


Here was my solution to this problem:

Datatable FI = new Datatable();
DataView viewFI = new DataView(FI);
viewFI.Sort = "ServiceDate, ServiceRoute";
DataTable OFI= viewFI.ToTable();
like image 44
Scooter Avatar answered Sep 16 '22 15:09

Scooter