按数字排序数组列表,然后按字母排序

bab*_*oon 5 c# sorting

我有字符串数组列表:

"1A", "12A", "12B", "6", "A", "5B", "B", "13".

如果我这样做,myList.Sort();那么我得到:

"1A", "12A", "12B", "13", "5B", "6", "A", "B".

但我需要的是先按照前面的数字排序,然后按字母排序:

"1A", "5B", "6", "12A", "12B", "13", "A", "B".

我可以用

public class CustomComparer : IComparer
{
    Comparer _comparer = new Comparer(System.Globalization.CultureInfo.CurrentCulture);

    public int Compare(object x, object y)
    {
        // Convert string comparisons to int
        return _comparer.Compare(Convert.ToInt32(x), Convert.ToInt32(y));
    }
}
Run Code Online (Sandbox Code Playgroud)

但它抛出异常.我如何得到我需要的东西?

Jon*_*eet 6

你的比较器太简单了.您的比较需要将每个值拆分为数字和其余值,然后首先比较数字,然后比较字符串是否相等.所以它会是这样的:

public sealed class NumberStringComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        return NumberString.Parse(x).CompareTo(NumberString.Parse(y));
    }


    private struct NumberString : IComparable<NumberString>
    {
        private readonly int? number;
        private readonly string text;

        private NumberString(int? number, string text)
        {
            this.number = number;
            this.text = text;
        }

        internal static NumberString Parse(string text)
        {
            // TODO: Find where the digits stop, parse the number
            // (if there is one), call the constructor and return a value.
            // (You could use a regular expression to separate the parts...)
        }

        public int CompareTo(NumberString other)
        {
            // TODO: Compare numbers; if they're equal, compare
            // strings
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您有一定的待办事项的问题(花了一些时间,试图),你可以要求更具体的帮助-但,这是一般的方法我会使用.


das*_*ght 5

你不能简单地传递一个字符串"1A""5B"Convert.ToInt32(x),因为它有一部分是没有的部分Int32.

相反,您应该首先将字符串拆分为两部分 - 数字和其他所有部分,然后使用tie tie进行比较.

一种方法是编写两个辅助方法,然后使用LINQ OrderByThenBy:

static int ExtractPrefix(string s) {
    // Parse the digits and stop; return the number
}
static string ExtractSuffix(string s) {
    // Skip digits, and return everything else
}
...
var sorted = unsorted.OrderBy(ExtractPrefix).ThenBy(ExtractSuffix).ToList();
Run Code Online (Sandbox Code Playgroud)

  • @babboon你需要在你的代码顶部添加`using System.Linq`,然后切换到`System.Collections.Generic.List <string>`,或在`unsorted之间添加`.Cast <string>()` `和`.OrderBy()`,即`unsorted.Cast <string>().OrderBy(ExtractPrefix).ThenBy(ExtractSuffix).ToList();` (2认同)