Carl H
Carl H

Reputation: 35

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 ?

Upvotes: 3

Views: 5317

Answers (2)

user23258132
user23258132

Reputation:

Yes you'd have to join stated from the previous example. Or simply use a loop formatted nicely to display the elements in the collection. Example:

in Java using .ToString() would print out the whole Collection

int [] array1 = new int{10, 20, 30};

you would get [10, 20, 30] in the output.

in C#:

int [] array1 = [10, 20, 30]

you would get System.Int32[]... in the output

So it's best to use a for loop for c#

for (int i = 0; i < array1.Length; i++)
{
    Console.WriteLine(array1[i]);
}

//remember that Console.WriteLine() automatically calls .ToString()

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

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) + "}");

Upvotes: 3

Related Questions