Hello. How to check whether elements are sorted in ascending alphabetical order in the listBox; if the elements are arranged in alphabetical order, then do not sort, if not in alphabetical order, then sort?

Tried so

listBox1.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription(listBox1.SelectedItems[i].ToString(), System.ComponentModel.ListSortDirection.Ascending)); int n = listBox1.Items.Count; string[] strmas = new string[n]; for (int ixdx = 0; ixdx < n; ixdx++) { strmas[ixdx] = listBox1.Items[ixdx].ToString(); } StringComparer comparer = StringComparer.InvariantCulture; Array.Sort(strmas, comparer); 
  • one
    It is easier to sort unconditionally, linear complexity on a sorted list. - karmadro4
  • @Demon, I’m not at all pleased with your percentage of accepted responses. I will not answer. - Olter

2 answers 2

Just try to set a flag. For example, if flag = false is not sorted, flag = true , and when sorting, set flag = true and check the flag in some handler, for example, when activating a form, etc. If I am of course I understand you correctly.

    I think to figure out what's going on.

     public bool IsSort(IEnumerable<object> list) { if (list.Count() <= 1) return true; IComparable Ai = list.ElementAt(0) as IComparable; if (Ai == null) throw new Exception("Содержание листа должно быть интерфейсом IComparable"); for (int i = 1; i < list.Count(); ++i) { IComparable Ai_1 = list.ElementAt(i) as IComparable; if (Ai_1 == null) throw new Exception("Содержание листа должно быть интерфейсом IComparable"); if (Ai.CompareTo(Ai_1) > 0) // Или "<" в зависимости от проверки возрастания или убывания return false; Ai = Ai_1; } return true; } 

    and in fact, sort and everything, I understand at the output you need to get a sorted array. Then what for to check whether it is sorted initially ??? Use FastSort.