C# 在字典中对数组排序

C# 在字典中对数组排序,c#,arrays,sorting,dictionary,C#,Arrays,Sorting,Dictionary,所以我写了这段代码,我不知道为什么它拒绝排序 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) { Di

所以我写了这段代码,我不知道为什么它拒绝排序

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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间SoloLearn
{
班级计划
{
静态void Main(字符串[]参数)
{
字典金属=新字典();
添加(“铂”,70);
添加(“铱”,20);
添加(“钯”,30);
添加(“钪”,12);
控制台。写入(“输入金属:”;
字符串metalName=Console.ReadLine();
控制台。写入(“输入价格:”;
int price=Convert.ToInt32(Console.ReadLine());
金属。添加(金属名称、价格);
int[]prices=metals.Values.ToArray();
数组.排序(价格);
int arraySize=prices.Length;
KeyValuePair KeyValuePair=金属.ElementAt(阵列大小-1);
字符串metalsKey=keyValuePair.Key;
WriteLine(“最昂贵的:{0}”,metalsKey);
Console.ReadKey();
}
}
}
它不会返回任何错误,所以我不知道问题出在哪里

请给我详细的解释。

当你打电话时

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

尝试一下
metalsKey=metals.OrderByDescending(x=>x.Value).First().Key
也只是一个调用,说明字典没有保证的顺序。所以不要依赖ElementAt来对抗字典,因为它毫无意义
var kvp = metals.OrderByDescending(v => v.Value).First();
Console.WriteLine("The most expensive is: {0} {1}", kvp.Key, kvp.Value);