Sorting rows of DataTable data by length in C #

How to make the following scenario: I have a DataTable that contains, for example, several lines:

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

How to sort strings by length, not by name. I wanted to sort the table by the length of the fields.

+4
source share
2 answers

You can add an additional column to your DataTable by specifying an expression containing the len() function call, as a result of which the column values ​​are automatically calculated:

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

Then you can simply sort your new column before binding the DataTable to the grid to any type of user interface control that you plan to use:

 table.DefaultView.Sort = "LengthOfName"; 
+11
source

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); } 
+1
source

Source: https://habr.com/ru/post/1286800/


All Articles