在c#中打印字典键值对

时间:2015-03-25 10:29:47

标签: c# dictionary

我有一个字典,它使用ulong作为键,结构作为值,即

  

public Dictionary<UInt64, OptimalOutputs> What_to_do>

最佳输出结构

public struct OptimalOutputs
    {
        public short gotoschool;
        public short goForDining;
        public short GoToAcademy;

    }

如何在字典中迭代打印,每个键和值一起? 我尝试了keyvalue对但是徒劳无功

2 个答案:

答案 0 :(得分:5)

foreach(KeyValuePair<UInt64, OptimalOutputs> pair in dict)
{
    Console.WriteLine("Key: {0} Values: {1},{2},{3}", 
        pair.Key,  
        pair.Value.gotoschool, pair.Value.goForDining, pair.Value.GoToAcademy);
}

您还可以在结构中覆盖ToString,这有助于f.e.调试:

public struct OptimalOutputs
{
    public short GotoSchool;
    public short GoForDining;
    public short GoToAcademy;

    public override string ToString()
    {
        return string.Format("{0}, {1}, {2}", GoForDining, GotoSchool, GoToAcademy);
    }
}

现在您可以使用这个较短的版本(隐式调用ToString):

foreach (KeyValuePair<UInt64, OptimalOutputs> pair in dict)
{
    Console.WriteLine("Key: {0} Values: {1}", pair.Key, pair.Value);
}

答案 1 :(得分:2)

您只需使用foreach次迭代:

foreach (KeyValuePair<UInt64, OptimalOutputs> pair in dictionary)
{
     Console.WriteLine(string.Format("Key: {0} ", pair.Key);
     Console.WriteLine(string.Format("Values: {0}, {1}, {2}", 
                                 pair.Value.goForDining,  
                                 pair.Value.gotoschool,                      
                                 pair.Value.GoToAcademy);
}

<强> 其他:

顺便说一句,您可以覆盖ToString()模型的OptimalOutputs

public class OptimalOutputs
{
    ...
    public override string ToString() 
      {
         return string.Format("Values: {0}, {1}, {2}", goForDining, gotoschool, GoToAcademy);
      }
    ...
}

然后:

foreach (KeyValuePair<UInt64, OptimalOutputs> pair in dictionary)
{
     Console.WriteLine(string.Format("Key: {0} Values: {1}", pair.Key, pair.Value);
}