user17753
user17753

Reputation: 3161

sort DataTable on one column independent of other columns

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?

Upvotes: 0

Views: 1114

Answers (2)

Bryan Roberts
Bryan Roberts

Reputation: 3479

It seems that maybe you should just regenerate the id column if you are just worried about the values of id after the sort.

table.Columns["id"].ReadOnly = false;
for (int i = 0; i < table.Rows.Count; i++)
{
    table.Rows[i]["id"] = i + 1;
}
table.Columns["id"].ReadOnly = true;

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use Linq-To-DataTable:

var orderedRows = table.AsEnumerable()
                       .OrderBy(r => r.Field<String>("name"));

or, if you just want the names:

var orderedNames = orderedRows.Select(r => r.Field<String>("name"));

Remember to add using System.Linq;.

Edit:

Each name belongs to an id. However, I only care about the id,name key,value pair after name has been sorted. E.g. the first alphanumerically sorted name should be 1, and the next 2, and so on

Then you need to add the rows after you've sorted the lines:

var txtLines = File.ReadLines(path)
                   .OrderBy(l => l);

foreach(String  line in txtLines)
    tables.Rows.Add(null, line);

Upvotes: 2

Related Questions