【问题标题】:Why does ArrayList.Sort() sorting by only first digit?为什么 ArrayList.Sort() 仅按第一位排序?
【发布时间】:2015-06-11 04:58:56
【问题描述】:

我有一个 c# 程序,它显示你输入的 10 个数字中的最大数字。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Ole
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            for (int i = 0; i < 10; i++)
            {
                list.Add(Console.ReadLine());
            }

            list.Sort();
            string Max = (string)list[list.Count - 1];
            Console.WriteLine("{0}", Max);
            Console.ReadLine();
        }
    }
}

但是,命令 list.Sort() 仅按第一个数字对其进行排序,例如:

24444 
1212 
2222 
555 
11 

会是这样的:

11
1212
2222
24444
555

如何按所有数字对列表进行排序以获得“真实”的最高数字?

【问题讨论】:

  • How can I sort list by all digits to get "real" highest number? ?不要使用 ArrayList 。使用List&lt;int&gt; 解析Console.ReadLine 为int,然后将其存储在泛型类型安全列表中。
  • 如果您真的需要以字符串前导类型对这些字符串进行排序,则使用零。取最大字符 24444 的长度,将其余字符更改为 00011、01212、00055... 等等。它们将按照编号进行排序。(或用空格引导它们)

标签: c# sorting console


【解决方案1】:

使用List&lt;int&gt; 代替ArrayList,并将控制台输入(string) 解析为数字(int)。

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>();
        for (int i = 0; i < 10; i++)
        {
            list.Add(int.Parse(Console.ReadLine()));
        }

        list.Sort();
        int Max = list[list.Count - 1];
        Console.WriteLine("{0}", Max);
        Console.ReadLine();
    }
}

请参阅ArrayList vs List<>,了解为什么现在使用List&lt;T&gt; 而不是ArrayList

【讨论】:

  • 这绝对是正确的做法。现在,如果 OP 还在摸不着头脑,想知道为什么它没有按照他的方式工作,他可能会发现知道他正在对字符串列表(Console.ReadLine() 的返回类型)而不是数字列表进行排序很有用。所以排序是按字母数字进行的,而不是数字。大不同。
猜你喜欢
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2021-11-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多