madiha malik
madiha malik

Reputation: 977

Printing dictionary key value pairs in c#

I have a dictionary which uses ulong as key and a structure as values, i.e.

public Dictionary<UInt64, OptimalOutputs> What_to_do>

Where optimaloutput structure is

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

    }

How can I iterate in dictionary to print, every key along with values? I tried keyvalue pair but in vain

Upvotes: 2

Views: 10491

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26645

You can simply use foreach iteration:

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

Additional:

By the way you can override ToString() for OptimalOutputs model.

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

And then:

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

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460148

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

You could also override ToString in your struct which helps f.e. debugging:

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

Now you can use this shorter version (ToString is called implicitly):

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

Upvotes: 7

Related Questions