-1

So I have a data table that has 4 columns, one column is 4,3,6,8,5 the next column is 2,3,4,7,5 and 2 more columns with just random numbers. I'm looking to organize the first column in ascneding orders and the rest of the columns follow so for example. 3,4,5,6,8 the 2nd column would be, 3,2,5,4,7. Thanks for the help~

PurpSchurp
  • 581
  • 5
  • 14
  • Have you tried anything, where did you get stuck? Also, what means _reorganize_ at all, do you want to reorder the rows or the columns? – Tim Schmelter Jun 11 '14 at 14:39
  • I'm sorry for lack of information. I haven't tried anything because i'm not quite sure how to sort it. I want to sort column 1 in ascending order and I want all the other columns to follow. thanks! – PurpSchurp Jun 11 '14 at 14:43
  • Im not sure if you have noticed that i have edited my answer to provide a VB.NET version. – Tim Schmelter Jun 11 '14 at 17:31

1 Answers1

1

You can use Linq-To-DataTable and Enumerable.OrderBy + CopyToDataTable:

tbl = tbl.AsEnumerable()
    .OrderBy(row => c[0])
    .ThenBy(row  => c[1])
    .CopyToDataTable();

With your sample data:

DataTable tbl = new DataTable();
tbl.Columns.Add("Col1", typeof(int));
tbl.Columns.Add("Col2", typeof(int));
tbl.Columns.Add("Col3", typeof(int));
tbl.Rows.Add(4, 2, 1);
tbl.Rows.Add(3, 3, 2);
tbl.Rows.Add(6, 4, 3);
tbl.Rows.Add(8, 7, 4);
tbl.Rows.Add(5, 5, 5);

Result:

3   3   2
4   2   1
5   5   5
6   4   3
8   7   4

Edit: only just noticed the VB.NET tag, it's more readable in VB.NET with query syntax:

Dim ordered = From row In tbl Order By row(0), row(1)
tbl = ordered.CopyToDataTable()
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939