4

How to do following scenario: I have some DataTable which contains for example some rows:

1.rowa
2.rowab
3.row
4.rowaba
...
n. rowabba

How to sort rows by lenght, not by name. I wan to to sort Table by length of fields.

nemke
  • 2,440
  • 3
  • 37
  • 57

2 Answers2

11

You could add an extra column to your DataTable, supplying an expression containing a call to the len() function, causing the column's values to be automatically computed:

table.Columns.Add("LengthOfName", typeof(int), "len(Name)");

Then you can simply sort on your new column before binding the DataTable to a grid to whatever kind of UI control you plan to use:

table.DefaultView.Sort = "LengthOfName";
Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
1

If you must use DataTable, you could introduce an extra column for the sort. In this case, you could set the value in the column simply to the length of each desired cell, and then sort by the new column:

        DataTable table = new DataTable();
        DataColumn val = table.Columns.Add("Value", typeof(string));
        table.Rows.Add("abc");
        table.Rows.Add("defgh");
        table.Rows.Add("i");
        table.Rows.Add("jklm");
        // sort logic: ***** schou-rode's "len(...)" approach is better *****
        DataColumn sort = table.Columns.Add("Sort", typeof(int));
        foreach (DataRow row in table.Rows) {
            row[sort] = ((string)row[val]).Length;
        }
        DataView view = new DataView(table);
        view.Sort = "Sort";
        foreach (DataRowView row in view) {
            Console.WriteLine(row.Row[val]);
        }

Personally, I'd use a typed list - of either a class, or a string in this case (since you only list one value):

        List<string> list = new List<string> {
            "abc", "defgh", "i", "jklm"};
        list.Sort((x, y) => x.Length.CompareTo(y.Length));
        foreach (string s in list) {
            Console.WriteLine(s);
        }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I'm agree, the simplest way is add a field like LENGTH(field) or LENGTH(field1 || field2 || ... || fieldN) to query of the Dataset – Jonathan Jun 26 '09 at 08:41
  • Or if you really really can't add columns, read out the rows through an iterator into a List. Sort the list, then add back in after clearing the table. Marc, thanks for the lambda expression. I'm still on C# 2, and was writing a test class implementing the Compare method. Gee, those lambda expressions sure do save a lot of lines... Wow. – maxwellb Jun 26 '09 at 08:45
  • Thanks for your answer, I would use typed list also, but I'm stuck with this code and it need to work yesterday :). If I change now to typed list I would need to change a lot of code – nemke Jun 26 '09 at 08:46
  • Well My DataTable does not contains one value. It has lots of value but I need to sort it by some key length, so I can later use String.Contains("jklm")... – nemke Jun 26 '09 at 08:52