2

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

2 Answers 2

7
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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

yeah thanx alot, i was missing value properties :)
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.