-1

So I was writing this code and I don't know why it refuses to sort.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoloLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> metals = new Dictionary<string, int>();
            metals.Add("Platinum", 70);
            metals.Add("Iridium", 20);
            metals.Add("Palladium", 30);
            metals.Add("Scandium", 12);


            Console.Write("Enter metal: ");
            string metalName = Console.ReadLine();
            Console.Write("Enter price: ");
            int price = Convert.ToInt32(Console.ReadLine());

            metals.Add(metalName, price);

            int[] prices = metals.Values.ToArray<int>();

            Array.Sort(prices);

            int arraySize = prices.Length;

            KeyValuePair<string, int> keyValuePair = metals.ElementAt(arraySize - 1);
            string metalsKey = keyValuePair.Key;
            Console.WriteLine("The most expensive: {0}", metalsKey);

            Console.ReadKey();
        }
    }
}

It doesn't return any errors so I don't know what the problem is.

I would love a detailed explanation please.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Kim Fom
  • 3
  • 1

1 Answers1

0

When you call

int[] prices = metals.Values.ToArray<int>();

you are creating a new integer array. This array contains a copy of the values in the dictionary, and sorting it doesn't change the order of the elements in the dictionary.

Moreover, a dictionary doesn't guarantee to maintain an order of its elements (as @pinkfloyd33 also points out in its comment).

Fortunately we have a better way to extract the most expensive item in that array using Linq

var kvp = metals.OrderByDescending(v => v.Value).First();
Console.WriteLine("The most expensive is: {0} {1}", kvp.Key, kvp.Value);
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    Also just a call out that Dictionaries *have no guaranteed ordering*. So don't rely on ElementAt against a Dictionary as it makes no sense at all – pinkfloydx33 May 10 '21 at 22:54