Question

in c# how do i add and then print the values in the following dictionary? Dictionary<String,...

in c# how do i add and then print the values in the following dictionary?

Dictionary<String, HashSet<String>> d

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,
Here in Dictionary<String, HashSet<String>> d, we have string key and HashSet as the value stored with the key. In C#, we can use the format specified below to add values in a dictionary.

1. Adding values
I am using an example of dictionary variable d, which contains key "Key 1" associated with HashSet values  "Value 1", "Value 2" and key "Key 2" associated with HashSet values  "Value 3", "Value 4".

Dictionary<String, HashSet<String>> d = new Dictionary<String, HashSet<String>>(); // Declaration and initialization of // dictionary variable d

d.Add("Key 1", new HashSet<string> { "Value 1", "Value 2" }); // Here key is "Key 1" and HashSet contains // values "Value 1"and "Value 2"
d.Add("Key 2", new HashSet<string> { "Value 3", "Value 4" });    // Here key is "Key 2" and HashSet contains // values "Value 3" and "Value 4"

2. Printing Values
We can use the following code to access and print each key and value in this dictionary.

foreach(var key_variable in d.Keys) // Loop to get each key in dictionary
{   
Console.WriteLine(key_variable.ToString()); // Printing key on console

foreach (var value in d[""+ key_variable]) // Loop to get each value in HashSet stored with the key
{
Console.WriteLine(value.ToString()); // Printing value in HashSet on console
}
}

You can use Messageboxes also to display the values.
I have pasted the console output of the above example in code.

That's all for now.
Please mention any queries or doubts in the comments section.
Thank You.

Add a comment
Know the answer?
Add Answer to:
in c# how do i add and then print the values in the following dictionary? Dictionary<String,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT