wpf C#在字符串数组中对文件名进行排序[已关闭]

6tqwzwtp  于 2022-11-30  发布在  C#
关注(0)|答案(1)|浏览(197)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

昨天关门了。
Improve this question
我在一个字符串数组中添加了一个文件名,用来显示组合框中的文件。但是它们没有正确排序。

有办法按字母和数字排序吗?
这是我用来将它们添加到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));
}

我试着按文件名的长度对它们进行排序,但这不起作用

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

qyuhtwio

qyuhtwio1#

您可以使用.OrderBy.ThenBy先依长度排序,然后再依字串内容排序。
但是,您可能希望使用一个数字排序器,它将数字视为数字而不是字符。这可以通过调用windows函数StrCmpLogicalW来实现,并使用一个 Package 器来实现排序所需的IComparable:

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);
    }

相关问题