Jon
Jon

Reputation: 40062

Ordering Datatable using Linq Or without creating copy of DataTable

I have the below code using System.Data.DataSetExtensions:

var orderedTable = myDataTable.AsEnumerable().OrderBy(x=>x["ID"].ToString())
myDataTable = orderedTable.CopyToDataTable();

Is this the easiest way to order the original datatable?

Upvotes: 0

Views: 540

Answers (3)

Surjit Samra
Surjit Samra

Reputation: 4662

Further to Stanley's ans you can do

 DataView dataView = new DataView(myDataTable);
      dataView.Sort = "ID";
     DataTable d = dataView.ToTable();

Upvotes: 1

Ron Sijm
Ron Sijm

Reputation: 8758

Creating a new object or changing the data type seems unnecessarily...

you can use Datatable.DefaultView.Sort

for example: myDataTable.DefaultView.Sort = "ID";

Upvotes: 1

D Stanley
D Stanley

Reputation: 152616

Use a DataView:

DataView dataView = new DataView(myDataTable);
dataView.Sort = "ID";

Note that it does not sort the actual DataTable, but gives you a view on top of it that is sorted.

Upvotes: 4

Related Questions