Sorting datagrid columns, i have code and its kinds of work

I am trying to sort columns of data from A to Z, the code below works, except that I get a column starting with 'c' between "A" (eg a, a, a, a, c, a, a, b, b, b), this happens the first time you run the code. If I then use columnNames.Reverse (); (Z to A) and then rerun columnNames.Sort () (A to Z), it sorts correctly. Why should it be?

 List<string> columnNames = new List<string>();
 foreach (DataGridViewColumn col in dataGridView1.Columns)
 columnNames.Add(col.HeaderText);
 columnNames.Sort();
 foreach (DataGridViewColumn col in dataGridView1.Columns)
     col.DisplayIndex = columnNames.IndexOf(col.HeaderText);

      

thank

0


source to share


1 answer


In your example ("(a, a, a, a, c, a, a, b, b, b)"), the column names are not unique. So, in the sorted list of names, the (first) index "a" will be 0, the (first) index "b" will be 5, and the (first) index "c" will be 8.

So, as you iterate over the columns, you will constantly set the columns with the text "a" to have an index of "0". The second time you do this, the first column at that position will be moved to make room. The result looks more like a shuffle of cards than a sort, and the final order depends on the original order. This is why the sort works great the second time β€” during your first pass, you are ordering the items "close enough" for the second attempt to succeed.



How about something like the following? It will assign the indices unambiguously and it will be more efficient as well. (Each call to IndexOf is O (N), so your original code is O (N ^ 2) - it's just O (N log N), at least assuming the collection of columns isn't reordered too much as the indexes are set.)

List<DataGridViewColumn> columns = new List<DataGridViewColumn>(dataGridView1.Columns);
columns.Sort( delegate(DataGridViewColumn a, DataGridViewColumn b) {
               return String.Compare( a.HeaderText, b.HeaderText ); }
int n = 0;
foreach( DataGridViewColumn col in columns )
   col.DisplayIndex = n++;

      

+1


source







All Articles