user1091406
user1091406

Reputation: 163

Fast sort dataTable

Is possible to do fast sort data in DataTable ?

I have a dataTable with a some rows (30k ~ 500k). I must sort in dataTable (not dataView etc). I have query with sory parameters so i use

var view = dataTable.DefaultView;
view.Sort = sortParameters;

var dataTable = view.ToTable();

This part is ok, and does very fast, but is one warning. If i use view.ToTable(), the new table doesn't have setted primaryKey. I must set that again, and this operation cost a lot of time :/

I can't change this. I must join two dataTables (with the same table definition but from other source) and return one with setted primaryKeys - how i say before i can't skip that.

Is any way to speed up this ?

Upvotes: 0

Views: 1322

Answers (1)

dwerner
dwerner

Reputation: 6602

Use LINQ if you can. It's the fastest way I've found. You'll need to reference DataSetExtensions, in .net 3.5. You'll end up with an IEnumerable instead of a table, however.

var drs = from x in dataTable.Rows
          where x.Field<someFieldType>("FieldName") == etc
          orderby x.Field<someFieldType1>('SortFieldName')
          select x;

Remove the where clause to sort only. Replace someFieldType and sortFieldName with your own values respectively.

on drs you can do .ToArray(), or import it to a DataTable, etc.

Upvotes: 2

Related Questions