I added a filename into a string array wich I use to display the files in a ComboBox. However they are not correctly sorted.
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));
CodePudding user response:
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);
}