Reputation: 41
I don't know how to print this :
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
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.List
1[System.String] => System.Collections.Generic.Dictionary2[System.String,System.Int32]
Upvotes: -1
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
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