Search code examples
c#listcountuniquedistinct

I need the loop to stop once 5 unique integers are entered into the list. The program runs but it does not stop when the unique numbers are entered


public void UniqueNumbers()
{
  List<int> valueList = new List<int>(); 
  int ListInput;
  var distinctCount = 0;
  
  while (distinctCount != 5) 
  {
    Console.WriteLine("Please enter an integer value: ");
    string? val = Console.ReadLine();
    ListInput = Convert.ToInt32(val);

    if (ListInput < 0 || ListInput > 100) 
    {
      valueList.Add(ListInput);
    }

    distinctCount = valueList.Distinct().Count();
  }
}

The integers would be placed in the list. Once the 5 unique numbers have been entered by the user, the loop should end. The if statement is to not allow numbers less than 0 or numbers greater than 100. The user will enter as many numbers as they need until 5 unique numbers are entered.


Solution

  • I need the loop to stop once 5 unique integers are entered into the list. The program runs but it does not stop when the unique numbers are entered

    Your code works. It breaks out of the loop after 5 unique numbers are in the list.

    The if statement is to not allow numbers less than 0 or numbers greater than 100.

    Here's your problem. You are not checking if the number is within 0 to 100. You are checking if it is outside that range. Any number between 0 and 100 is not being added to the list. You want to flip the check like this:

    if (ListInput >= 0 && ListInput <= 100) 
    {
      valueList.Add(ListInput);
    }
    

    You can easily verify this (and debug similar problems in the future) by running your code with a debugger attached and stepping through the code line-by-line.