Kristiyan Kitov
Kristiyan Kitov

Reputation: 41

Printing Dictionary in c#

I don't know how to print this :

enter image description here

in this format :

destroyer: 
192.23.30.40 => 2,
192.23.30.41 => 1,
192.23.30.42 => 1

can someone do it ?

Upvotes: 1

Views: 8201

Answers (3)

Kristiyan Kitov
Kristiyan Kitov

Reputation: 41

mmm both of the ways does not work , i need to print "destroyer" also , but destroey must be printed from the dictionary, when i try

`foreach (KeyValuePair<string, int> item in dictAndNames)

{ Console.Write(item.Key+"=>" + item.Value.ToString());
} `

there is an error that cant convert, and when i try this

`Console.WriteLine(string.Join(", ", dictAndNames.Select(pair => $"{pair.Key} => {pair.Value}")));`

console says : System.Collections.Generic.List1[System.String] => System.Collections.Generic.Dictionary2[System.String,System.Int32]

Upvotes: -1

Stefano d&#39;Antonio
Stefano d&#39;Antonio

Reputation: 6152

You can use LINQ to get a collection of strings representing your entries and join them:

Console.WriteLine(string.Join(", ", dictAndNames.Select(pair => $"{pair.Key} => {pair.Value}")));

Explained:

// Method to take all the pairs and format them as the string you like:
Func<KeyValuePair<string, int>, string> selector = 
     pair => $"{pair.Key} => {pair.Value}";

// Convert all the elements in the dictionary:
var values = dictAndNames.Select(selector);

// Join them with the separator you like (you can also use Environment.NewLine):
var joined = string.Join(", ", values);

// Print:
Console.WriteLine(joined);

If you are not using C# 6 as pointed out, you can simply replace the string interpolation with a string.Format invocation:

string.Format("{0} => {1}", pair.Key, pair.Value)

Upvotes: 5

Sajeetharan
Sajeetharan

Reputation: 222582

You can do this,

Loop over the KeyValuePair in the dictionary dictAndNames

   foreach (KeyValuePair<string, int> item in dictAndNames)
   {
      Console.Write(item.Key+"=>" + item.Value.ToString());               
   }     

Upvotes: 2

Related Questions