Search code examples
c#ienumerableconsole.writeline

Is there a way to write whole IEnumerable<T> within one Console.Write(line)?


I have the following code

    IEnumerable<int> numbers = 
        Enumerable.Range(1, 5)
        .Reverse();
    Func<int, string> outputFormat = x => x + "...";
    IEnumerable<string> countdown = numbers.Select(outputFormat);
    foreach (string s in countdown)
    {
        Console.WriteLine(s);
    }

Is there a way to "eliminate" foreach loop from the code, something like

Console.Write(countdown.EnumerateOverItems())

without actually writing custom method (e.g. using LINQ or delegates somehow)?


Solution

  • This should do the trick:

    Console.WriteLine(string.Join(Environment.NewLine, countdown));