用数字排序数组列表,然后通过信件 [英] Sort array list by numbers then by letters

查看:144
本文介绍了用数字排序数组列表,然后通过信件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组列表:

I have array list of strings:

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

如果我 myList.Sort(); 然后我得到:

1A,12A,12B,13,5B,6,A,b

不过,我需要的是在前面的数字先排序,然后通过信函:

But what I need is first sort by numbers in front, then by letter:

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



但它抛出异常。我如何得到我需要什么?

But it throws exception. How do I get what I need?

推荐答案

您不能简单地传递一个字符串1A5B Convert.ToInt32(X),因为它有一个部分是。不是的Int32

You cannot simply pass a string "1A" or "5B" to Convert.ToInt32(x), because it has a portion that is not part of an Int32.

相反的一部分,你应该首先将字符串分割成两部分 - 数字和一切否则,做领带休息的比较。

Instead, you should first split the string into two parts - the digits and everything else, and do the comparison with tie breaks.

这样做会写两个辅助方法,再利用的方法之一LINQ的排序依据 ThenBy

One way of doing it would be writing two helper methods, and then using LINQ's OrderBy and ThenBy:

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

这篇关于用数字排序数组列表,然后通过信件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆