在c#中打印字典

时间:2016-10-08 16:20:43

标签: c# dictionary

我不知道如何打印这个:

enter image description here

采用以下格式:

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

有人可以吗?

3 个答案:

答案 0 :(得分:1)

您可以使用 LINQ 来获取代表您的条目的字符串集合并加入它们:

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

说明:

// 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);

如果你没有使用 C#6 ,你可以简单地用string.Format调用替换字符串插值:

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

答案 1 :(得分:0)

你可以这样做,

在字典 class MigrateStoryTypes < ActiveRecord::Migration def self.up Story.all.each { |story| new_story_type = story.story_type.camelize + 'Story' puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}" story.update_column :story_type, new_story_type } end def self.down Story.all.each { |story| new_story_type = story.story_type.underscore.gsub /_story/, '' puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}" story.update_column :story_type, new_story_type } end end

中循环 KeyValuePair
dictAndNames

答案 2 :(得分:0)

mmm两种方式都不起作用,我也需要打印“驱逐舰”,但是当我尝试时,必须从字典中打印出破坏物

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

{       Console.Write(item.Key +“=&gt;”+ item.Value.ToString());
   }`

有一个错误,无法转换,当我尝试这个

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

控制台说:System.Collections.Generic.List 1 [System.String] =&gt; System.Collections.Generic.Dictionary 2[System.String,System.Int32]