If you must use a DataTable , you can enter an additional column for sorting. In this case, you can set the value in the column simply by the length of each required 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 "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 would use a typed list - both a class and a string in this case (since you only list a single 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); }
source share