Reputation: 977
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
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
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