I create a two column DataTable (id, name):
DataTable table = new DataTable();
DataColumn id = table.Columns.Add("id", typeof(int));
id.AutoIncrement = true;
id.AutoIncrementSeed = 1;
id.AutoIncrementStep = 1;
id.ReadOnly = true;
table.Columns.Add("name", typeof(String));
The DataColumn named id is AutoIncrementing (e.g. identity).
Then I read a file, and add each line of the file as a row.
//for each line in file
table.Rows.Add(null,line);
Next, I sort the DataTable on the DataColumn named name using a DataView:
DataView dv = table.DefaultView;
dv.Sort = "name";
table = dv.ToTable();
Problem is, the id column gets sorted when I would prefer it not (basically I just want to sort the name column independently of the other column).
Only solution I could find was to have an intermediate step where I populate a List<string> with the file lines, then sort that, then populate the table. Wondering if there was a more elegant (simple) solution?
You can use
Linq-To-DataTable:or, if you just want the names:
Remember to add
using System.Linq;.Edit:
Then you need to add the rows after you’ve sorted the lines: