-1

I added a filename into a string array wich I use to display the files in a ComboBox. However they are not correctly sorted.

enter image description here

Is there a way to sort them by letter and number?

This is the code I used to add them to the ComboBox

string[] FilePaths = Directory.GetFiles(_infr.Konfig.Betrieb.RegelungsdatenPfad.Pfad);  //Creating a string array to store the File Name of the Processdata

foreach (string file in FilePaths)  //Adding the Files into the String Array
{
    comboBox1.Items.Add(Path.GetFileName(file));
}

I tried to Sort them by the Length of the Filename but that didnt work the way it would

Array.Sort(FilePaths, (x, y)=\>x.Length.CompareTo(y.Length));

enter image description here

Fildor
  • 14,510
  • 4
  • 35
  • 67
Zaros
  • 9
  • 2
  • You haven't explained how you want the filename items to be sorted. – Peregrine Nov 29 '22 at 08:51
  • In your second image they **do** seem to be sorted on length? Do you want to sort them on length and string? – Okke Hendriks Nov 29 '22 at 08:52
  • @OkkeHendriks i want them to be sorted by letter and number so its displayed RL_1.001, RL_1.002, RL_2.001, RL_2.002 and going on – Zaros Nov 29 '22 at 08:56
  • Strings are sorted lexically. I guess you do not have any say in the naming of the files? If so, you could use for example leading 0s: "RL_01.001" ... Like it is done in the section after the dot. – Fildor Nov 29 '22 at 09:00
  • ^^ Of course, you can go wild, split the name in a string and a number part, parse the numerical part and sort numerically (or then mixed). But looking at the size of the scrollbar, that could begin to be noticeably slow. – Fildor Nov 29 '22 at 09:03
  • Does this answer your question? [Natural Sort Order in C#](https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp) – Selvin Nov 29 '22 at 09:26

1 Answers1

3

You could use .OrderBy and .ThenBy to first sort by length, and then by string content.

But you might want to use a numerical sorter that treats numerical digits as numbers and not as characters. This can be done by calling the windows function StrCmpLogicalW, with a wrapper to implement the IComparable that is needed for sorting:

    public static class Win32Api
    {
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        public static extern int StrCmpLogicalW(string psz1, string psz2);
    }

    public class NaturalNumberSort : IComparer<string>
    {
        public static readonly NaturalNumberSort Instance = new NaturalNumberSort();
        public int Compare(string x, string y) => Win32Api.StrCmpLogicalW(x, y);
    }
JonasH
  • 28,608
  • 2
  • 10
  • 23