【问题标题】:Sorting an Array in Dictionaries [duplicate]对字典中的数组进行排序[重复]
【发布时间】:2021-05-10 21:54:57
【问题描述】:

所以我正在编写这段代码,但我不知道它为什么拒绝排序。

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();
        }
    }
}

它没有返回任何错误,所以我不知道问题是什么。

请给我详细的解释。

【问题讨论】:

  • 试试metalsKey = metals.OrderByDescending( x =&gt; x.Value ).First().Key

标签: c# arrays sorting dictionary


【解决方案1】:

当你打电话时

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

您正在创建一个新的整数数组。此数组包含字典中值的副本,对其进行排序不会更改字典中元素的顺序。

此外,其元素的dictionary doesn't guarantee to maintain an order (正如@pinkfloyd33 也在其评论中指出的那样)。

幸运的是,我们有一个更好的方法来提取使用 Linq 数组中最昂贵的项目

var kvp = metals.OrderByDescending(v => v.Value).First();
Console.WriteLine("The most expensive is: {0} {1}", kvp.Key, kvp.Value);

【讨论】:

  • 还只是指出字典没有保证排序。所以不要依赖 ElementAt 来对抗 Dictionary,因为它根本没有意义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 2015-12-26
相关资源
最近更新 更多