Search code examples
pythonc#pprint

Is there a C# equivalent to Python's pprint?


More specifically, I have an collection of string elements in C# that I want to print out like so:

{ "Element 1", "Element 2", "Element 3" }

Is there a library already built to do this? I know I could write a little bit of code for myself but I am curious. In python, if I had a list, I could easily print out the list with nice formatting like so.

import pprint
my_list = ['foo', 'bar', 'cats', 'dogs'] 
pprint.pprint(my_list)

which would yield me ['foo', 'bar', 'cats', 'dogs'] to the console.

Comma separated values are fine, I do not need the curly brackets or other formatting.


Solution

  • You can do it with string.Join(),

    Concatenates the members of a constructed IEnumerable collection of type String, using the specified separator between each member.

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    ...
    var result = string.Join(", ", my_list);  //Concatenate my_list elements using comma separator
    Console.WriteLine(result);               //Print result to console
    

    .Net Fiddle