0

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?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Koty97
  • 35
  • 7
  • 1
    `How can I sort list by all digits to get "real" highest number?` ? Do not use `ArrayList` . Use `List` parse `Console.ReadLine` to int and then store it in a generic type safe list. – Habib Jun 10 '15 at 20:39
  • If you really nead to sort this strings in type of string lead then with zero. Take the length of most great character 24444 change the rest with 00011, 01212, 00055... so on. They will be sorted as well as they are number.(or lead them with space) – Ismail Gunes Jun 11 '15 at 00:27

1 Answers1

5

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.

Community
  • 1
  • 1
Cyral
  • 13,999
  • 6
  • 50
  • 90
  • 2
    This is definitely the right thing to do. Now, if OP is still scratching his head wondering why it didn't work his way, he may find it useful to know that he was sorting a list of strings (the return type of `Console.ReadLine()`), not a list of numbers. So the sorting was performed alphanumerically, not numerically. Big difference. – sstan Jun 10 '15 at 20:58