Help with Dictionary<U, V> | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help with Dictionary<U, V>

I need help with this exercise, it generates an error in the output. The program you are given defines a metal dictionary, where names are used as keys and their price per 1 gram as values. Take the name and price of the fifth metal as input. Add the 5th pair to the dictionary and write the code to get the message about the most expensive metal in the dictionary. Input example Rhodium 225 Output example The most expensive: Rodio Track The given line int [] prices = metals.Values.ToArray () creates an array with the dictionary values. You must order its elements, and the last element will be the largest. So you should find a way to get the key that has that maximum value in the dictionary. The Keys property gets an indexed collection that contains only the keys contained in the dictionary. This is my code: https://code.sololearn.com/c97Ti7bP2nhh/?ref=app

9th Jul 2021, 5:36 PM
Alex Narváez
Alex Narváez - avatar
4 Answers
+ 1
Alex Narváez You added Semicolon (;) after if statement which is wrong. You have to add break inside if condition and also there is space after colon (:) foreach (string s in metals.Keys) { if (metals[s] == prices[4]) { Console.Write("The most expensive: " + s); break; } }
9th Jul 2021, 6:08 PM
A͢J
A͢J - avatar
+ 1
Alex Narváez metals[s] is a int value because dictionary have key String and value int so here s is a String and metals[s] will give corresponding value which is type int and int cannot contain ContainsValue method. So do metals[s] == prices[4] and also add break inside the condition.
9th Jul 2021, 5:44 PM
A͢J
A͢J - avatar
+ 1
Haa, now I understand better and what was missing. Thank you I ᴀᴍ "Tɪᴍᴇ"
9th Jul 2021, 6:31 PM
Alex Narváez
Alex Narváez - avatar
0
I understand, however in the If statement I don't understand why it should be the same. Likewise the code does not work that way.
9th Jul 2021, 5:58 PM
Alex Narváez
Alex Narváez - avatar