3

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 ?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Carl H
  • 35
  • 1
  • 4
  • Existing suggestion (not making Java comparison so) - Dictionary/HashSet - http://stackoverflow.com/questions/5899171/is-there-anyway-to-handy-convert-a-dictionary-to-string/17281317, any type of collection for any element type - http://stackoverflow.com/questions/5079867/c-sharp-ienumerable-print-out – Alexei Levenkov Aug 02 '16 at 16:37

1 Answers1

2

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) + "}");
René Vogt
  • 43,056
  • 14
  • 77
  • 99