Why does ArrayList.Sort() sorting by only first digit?

836 views Asked by At

I have program in c#, that shows you highest number from 10 numbers you enter.

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

But, command list.Sort() sorts it by only first digit, example:

24444 
1212 
2222 
555 
11 

Will be sort like:

11
1212
2222
24444
555

How can I sort list by all digits to get "real" highest number?

1

There are 1 answers

1
Cyral On BEST ANSWER

Use a List<int> instead of ArrayList, and parse the console input (string) into a number (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();
    }
}

See ArrayList vs List<> for why List<T> is used instead of ArrayList now.