Waqas Ali
Waqas Ali

Reputation: 189

Copying sorted values from one datatable to another Efficiency?

I am using the following code :

        EmpInfoDS = new DataSet();

        con.Open(); // My connection name

        string sqlRecords = "Select * FROM tbl_EmpInfo";
        EmpInfoDA = new OleDbDataAdapter(sqlRecords, con);
        EmpInfoDA.Fill(EmpInfoDS, "EmpInfo");

            var sortedRows = (from myRow in EmpInfoDS.Tables["EmpInfo"].AsEnumerable()
                             orderby myRow["EmpID"] ascending
                             select myRow).ToArray();

            EmpInfoDS.Tables.Remove("EmpInfo");
            DataTable EmpInfo = sortedRows.CopyToDataTable();
            EmpInfo.TableName = "EmpInfo";
            EmpInfoDS.Tables.Add(EmpInfo); 

        con.Close();

to sort the values in a datatable. Then removing that datatable and filling the sorted rows into a datatable with the same name. Can anyone tell me how much efficient this process is. ie. Performance drawbacks ???

If there's a better way to accomplish this; Please tell me.

Any help will be much appreciated. :)

Upvotes: 0

Views: 1266

Answers (2)

George Dgebuadze
George Dgebuadze

Reputation: 111

You can try

    EmpInfoDS.Tables["EmpInfo"].Sort = "EmpID ASC";
    DataTable EmpInfo = EmpInfoDS.Tables["EmpInfo"].DefaultView.ToTable();
    EmpInfoDS.Tables.Add(EmpInfo);
    //To remove sorting  --- EmpInfoDS.Tables["EmpInfo"].Sort = string.Empty;

with this approach you may leave your old DataTable and change sorting expression

Upvotes: 1

Koenyn
Koenyn

Reputation: 704

Why don't you just order by in the database? That will always be way more efficient.

i.e.

EmpInfoDS = new DataSet();
con.Open(); // My connection name
string sqlRecords = "Select * FROM tbl_EmpInfo ORDER BY EmpID";
EmpInfoDA = new OleDbDataAdapter(sqlRecords, con);
EmpInfoDA.Fill(EmpInfoDS, "EmpInfo");
con.Close();

Always let the database do work that it's made to do. Sorting is a database function and not a C# function (when it comes to fetching data)

Upvotes: 4

Related Questions