【问题标题】:How to sort this dictionary by key如何按键排序这个字典
【发布时间】:2018-12-20 15:59:52
【问题描述】:

当我点击按钮时,我想按键排序这个字典。它应该是这样的:https://gyazo.com/2f03244e94627153e8f7cb3fef4862d5

试图用冒泡排序以某种方式做到这一点,但无法弄清楚。

public partial class MainWindow : Window
{
    Dictionary<int, string> dict = new Dictionary<int, string>();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btn_add_Click(object sender, RoutedEventArgs e)
    {

        //Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Clear();

        //int asd = Convert.ToInt32(txt1.Text);
        string asd = Convert.ToString(txt2.Text);

        dict.Add(Convert.ToInt32(txt1.Text), asd);

        string lol = "";

        foreach (var pair in dict)
        {
            lol += pair.Key + "-" + pair.Value;
        }

        list.Items.Add(lol);
    }

    private void btn_sort_Click(object sender, RoutedEventArgs e)
    {
        int asd = dict.ElementAt(1).Key;

         for (int i = 1; i < dict.Count; i++)
         {
             for (int j = i + 1; j < dict.Count; j++)
             {
                 if (dict.ElementAt(i).Key > dict.ElementAt(j).Key)
                 {


                     asd = dict.ElementAt(i).Key;

                     dict.ElementAt(i).Key = dict.ElementAt(j).Key;

                     dict.ElementAt(j).Key = asd;
                 }
             }
         }
   }

【问题讨论】:

  • 字典是无序的。
  • 你尝试过 SortedDictionary 吗?
  • 可以使用dict.OrderBy((kvp) => kvp.Key);进行排序
  • @jdweng 不知道该怎么做。尝试过这样的事情但不起作用gyazo.com/0ae0f663ef23f99125ff76c91d16269b
  • 它必须有效。它像排序一样缠绕,但不是您期望的顺序。哪些值没有排序?

标签: c# wpf sorting dictionary


【解决方案1】:

您可能希望使用SortedList 类而不是字典。字典是一个哈希表,与你打算做的有不同的用法。

【讨论】:

    【解决方案2】:

    如果您只想按键顺序打印出无序字典的内容,则使用OrderBy对字典进行排序

    public void PrintSortedDictionary(Dictionary<int, string> dictionary)
    {
        dictionary.OrderBy(kvp => kvp.Key).ToList().ForEach(kvp => Console.WriteLine($"Key: {kvp.Key} - Value: {kvp.Value}"));
    }
    

    【讨论】:

    • 它是一个 wpf,所以我不想用 consolewriteline 打印出来
    • 字典的排序没有改变,只是按键排序。对字典进行排序后,您可以随心所欲,将内容放在标签、字符串或任何您需要的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2011-06-17
    • 2021-04-24
    • 2016-08-31
    • 2015-10-10
    • 2012-07-30
    相关资源
    最近更新 更多