2

I'm currently doing a beginner's coding exercise, and have run into a problem. The program I made takes 5 numbers, turns them into an array, and displays the three smallest numbers on the console. I have the input separated into an array, and created a new variable containing the three smallest values, but I'm not sure how to display each number in the array on the console. I know that's a beginner question, but I've been coding less than a week. I tried searching StackOverflow and found a code to display each integer in a list, but am unsure what to change to display each value in an array.

bool isFive = new bool();
Console.WriteLine("Enter at least 5 numbers, separated by a comma.");

while (!isFive)
{
    string text = Console.ReadLine();
    string[] result = text.Split(',');
    int[] resultInt = result.Select(s => int.Parse(s)).ToArray();
    if (resultInt.Length < 5)
    {
        Console.WriteLine("Invalid list, retry.");
    }
    else
    {
        isFive = true;
        var smallestThree = resultInt.OrderBy(x => x).Take(3);
        ????????????????
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
JohnZ12
  • 183
  • 3
  • 14
  • Possible duplicate of [printing all contents of array in C#](https://stackoverflow.com/questions/16265247/printing-all-contents-of-array-in-c-sharp) – Paulo Pereira Oct 01 '18 at 14:40
  • 2
    Seems like you're attempting to run before you can walk - you're using some Linq without understanding the basics of looping over the contents of an array using a `for` or a `foreach` loop. I would start there. Read [this](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/using-foreach-with-arrays) and [this](https://www.dotnetperls.com/loop-string-array) for example. – Matthew Watson Oct 01 '18 at 14:45

1 Answers1

4

Almost there. All you need is string.Join:

Console.WriteLine(string.Join(", ", resultInt.OrderBy(x => x).Take(3)));

Also, instead of using int.Parse have a look at int.TryParse: Select parsed int, if string was parseable to int

Gilad Green
  • 36,708
  • 7
  • 61
  • 95