Search code examples
c#dictionarycollections

Can C# print collection values as simple as Java does?


In Java I can print values of collection just passing collection to output:

Map<Integer, String> map = new HashMap<Integer, String>(){
            {
                put(1, "one");
                put(2, "two");
            }
};
System.out.println(map);

Output:

{1=one, 2=two}

In C# similar code would give me info about collection types, instead of values inside, I've been looking for it, but as I understand in C# you have to work around to get output of values from collection. As I understand with C# you can't show values of collection as simple as using Java, am I right ?


Solution

  • When passing an object of any type to - say - Console.WriteLine(), the ToString() method of that object is called to convert it to a printable string.

    The default implementation of ToString() returns the type name. Some collections have overridden implementations of ToString() that return a string containing information like the number of elements in the collection.

    But by default there is no such functionality as in your java example.

    A simple way to get such an output would be to use string.Join and some LINQ:

    Console.WriteLine("{" + string.Join(", ", map.Select(m => $"{m.Key}={m.Value}")) + "}");
    

    If the elements in your collection already have a proper .ToString() implementation (like e.g. KeyValuePair<TKey, TValue> as Michael LY pointed out), you can skip the Select part:

    Console.WriteLine("{" + string.Join(", ", map) + "}");