Search code examples
c#listconsoleconsole-applicationtext-based

C# Simple console application displaying/logical issue


        List<int> numberList = new List<int>();
        List<int> uniqueList = new List<int>();

        string input;
        int number = 0;
        bool over = false;

        while (!over)
        {
            input = Console.ReadLine();
            if (input == "quit")
            {
                over = true;
                break;
            }
            if (int.TryParse(input, out number))
            {
                numberList.Add(number);
            }
        }

        for (int i = 0; i < numberList.Count; i++)
        {
            if (!uniqueList.Contains(number))
            {
                uniqueList.Add(number);
            }
        }

        for (int i = 0; i < uniqueList.Count; i++)
        {
            Console.WriteLine(uniqueList[i]);
        }

        Console.ReadKey();

Hi! I need some help with this program that takes in numbers, but upon typing "quit", it should list all the unique numbers that have been entered.

For example here's the input: 5, 5, 5, 2, 2, 1, 3 The console should only display 1 and 3 because they are the only unique numbers.

The problem is, that the program in its current form only displays the last unique number that has been entered, not all of them and I don't know why.

Could you tell me why? What do I need to do to list all of them?


Solution

  • You need to use a Dictionary to record the count of each number, then return the unique ones:

        Dictionary<int, int> numberDictionary = new Dictionary<int, int>();
    
        string input;
        int number = 0;
        bool over = false;
    
        while (!over)
        {
            input = Console.ReadLine();
            if (input == "quit")
            {
                over = true;
                break;
            }
            if (int.TryParse(input, out number))
            {
                if (numberDictionary.TryGetValue(number), out int count)
                {
                    numberDictionary[number] = count + 1;
                }
                else
                {
                    numberDictionary.Add(number, 1);
                } 
            }
        }
    
        foreach(var item in numberDictionary)
        {
            if (item.Value == 1)
            Console.WriteLine(item.Key);
        }
    
        Console.ReadKey();