You've got a few options:
Console.WriteLine()
outputs whatever string you give it and starts a new line of text after it - akin to when we type and press the enter key.
Console.Write()
outputs whatever string you give it - no more, and no less.
So you could simply replace the WriteLine
in the loop with a Write
...
Or you could build the entire string and pass it to a WriteLine()
, something like:
List<string> numbersInput = new List<string>();
Console.WriteLine("Please enter an integer: ");
string input1 = Console.ReadLine();
while (!string.IsNullOrEmpty(input1))
{
numbersInput.Add(input1);
Console.WriteLine("Please enter another integer: ");
input1 = Console.ReadLine();
}
if (numbersInput.Count > 0)
{
Console.WriteLine("You have entered " + numbersInput.Count + " numbers, they were: ");
var a = 1;
var s = "";
foreach (var input in numbersInput)
{
s = $"{s}, Number {a++} = \t{input}"; //string interpolation only applicable post C# 7
}
Console.WriteLine(s.Trim(", "));
}
else
{
Console.WriteLine("You have entered 0 numbers.");
}
In the comments, Lasse suggests Console.WriteLine("Numbers: " + string.Join(", ", numbersInput));
(instead of the foreach
loop) which would potentially be more efficient... but would have a different output format to your original question.
Alternatively, if you want to maintain the output format of your question, you could rejig things to use a Dictionary
instead of a List
. For instance:
Dictionary<string, string> numbersInput = new Dictionary<string, string>();
Console.WriteLine("Please enter an integer: ");
string input1 = Console.ReadLine();
var x = 1;
while (!string.IsNullOrEmpty(input1))
{
//numbersInput.Add(input1);
numbersInput.Add(input1, $"Number {x} = \t{input1}");
x++;
Console.WriteLine("Please enter another integer: ");
input1 = Console.ReadLine();
}
if (numbersInput.Count > 0)
{
Console.WriteLine("You have entered " + numbersInput.Count + " numbers, they were: ");
Console.WriteLine(string.Join(", ", numbersInput.Values));
}
else
{
Console.WriteLine("You have entered 0 numbers.");
}