如何按字母顺序对字符串进行排序,同时考虑到其中包含数字的情况?

126

我在尝试对一个由字符串组成的数字数组进行排序,希望按照数值大小排序。

但是问题在于我不能将这些数字转换为整数。

以下是代码:

string[] things= new string[] { "105", "101", "102", "103", "90" };

foreach (var thing in things.OrderBy(x => x))
{
    Console.WriteLine(thing);
}

输出:

101, 102, 103, 105, 90
我希望拥有:

我希望:

90, 101, 102, 103, 105

编辑: 输出不能为090, 101, 102...

更新了代码示例,将“sizes”更改为“things”。 数组可能像这样:

string[] things= new string[] { "paul", "bob", "lauren", "007", "90" };

这意味着需要按字母和数字进行排序:

007, 90, bob, lauren, paul

9
为什么不能将它们转换为整数? - Femaref
2
"Sizes" 可以是其他类似于 "name" 的东西。代码示例只是简化的。 - sf.
4
这些数字中会有负数吗?它们都是整数吗?整数的范围是什么? - Eric Lippert
1
“things” 可以是任何类型的字符串。我希望列表按照对非计算机专业人士有意义的逻辑顺序排序。负数应该排在正数之前。就字符串长度而言,它不会超过100个字符。 - sf.
7
你想走多远? image10 应该在 image2 之后吗? January 应该在 February 之前吗? - svick
显示剩余3条评论
24个回答

0
我本想在recursive的回答下面留言,但我的声望还不够。
因为recursive的答案只适用于数字字符串(如果您有一个字符串像“我只是一个非常长的字符串”,它会在“不那么长的字符串”之后排列),而且OP已经编辑了他的回答,所以我对这个问题的想法是将字符串区分为数字和非数字,然后进行排序。
int maxlen = items.Max(x => x.Length);
var items  = items.OrderBy(x => long.TryParse(x, out _) == true ? x.PadLeft(maxlen, '0') : x);

下划线用于丢弃输出。

0

我的首选解决方案(如果所有字符串都只包含数字):

// Order by numerical order: (Assertion: all things are numeric strings only) 
foreach (var thing in things.OrderBy(int.Parse))
{
    Console.Writeline(thing);
}

-1
namespace X
{
    public class Utils
    {
        public class StrCmpLogicalComparer : IComparer<Projects.Sample>
        {
            [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
            private static extern int StrCmpLogicalW(string x, string y);


            public int Compare(Projects.Sample x, Projects.Sample y)
            {
                string[] ls1 = x.sample_name.Split("_");
                string[] ls2 = y.sample_name.Split("_");
                string s1 = ls1[0];
                string s2 = ls2[0];
                return StrCmpLogicalW(s1, s2);
            }
        }

    }
}

-2

虽然这是一个老问题,但我想提供一个解决方案:

string[] things= new string[] { "105", "101", "102", "103", "90" };

foreach (var thing in things.OrderBy(x => Int32.Parse(x) )
{
    Console.WriteLine(thing);
}

哇,非常简单吧? :D


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接