将字典值按降序排序

时间:2020-05-11 02:17:33

标签: c#

我的任务

  1. 从用户那里获取字符串
  2. 找出字符串中每个字符重复多少次
  3. 找到重复频率最低的两个字符,并将其与频率总和相加
  4. 将此新金额重新添加到列表中,无论现在到哪里,都更高
  5. 重复这些步骤,直到有霍夫曼树!

我的代码:

class Program
{
    static void Main(string[] args)
    {
        HuffmanTree.GetValue();
    }
}

class HuffmanTree
{
    public static void GetValue()

    {
        Console.WriteLine("Write a string to be encoded"); //Here we are asking the user to input a string
        string encodeme = Console.ReadLine(); // here the user inputs their string, which gets declared as the variable "encodeme"

        Dictionary<char, int> timesRepeated = new Dictionary<char, int>();

        foreach (char ch in encodeme.Replace(" ", string.Empty))
        {
            if (timesRepeated.ContainsKey(ch))
            {
                timesRepeated[ch] = timesRepeated[ch] + 1;
            }
            else
            {
                timesRepeated.Add(ch, 1);
            }
        }

        foreach (var item in timesRepeated.Keys)
        {
            Console.WriteLine(item + " : " + timesRepeated[item]);
        }

        Console.ReadKey();
    }
}

class Node
{

}

因此,我尝试将字典值“重复次数”以降序排列,以便当它打印出重复字符的次数时,它以降序显示这些值。

例如,如果我输入字符串“ BOOOM”

O = 3
B = 1
M = 1

此刻它说:

B = 1
O = 3
M = 1

我不确定该怎么做!

1 个答案:

答案 0 :(得分:1)

目前您正在枚举键集合,但是实际上您可以枚举字典本身,这意味着您将获得键/值对象:

foreach(KeyValuePair<char, int> item in timesRepeated)
{
    char key = item.Key;
    int count = item.Value;
    Console.WriteLine(key.ToString() + " : " + count.ToString());
}

这如何帮助我们?好吧,我们可以将其与.OrderByDescending LINQ方法结合起来:

foreach(KeyValuePair<char, int> item in timesRepeated.OrderByDescending(i => i.Value))
{
    char key = item.Key;
    int count = item.Value;
    Console.WriteLine(key.ToString() + " : " + count.ToString());
}

您可能还想按字母顺序排序,然后可以使用ThenBy

foreach(KeyValuePair<char, int> item in timesRepeated.OrderByDescending(i => i.Value).ThenBy(i => i.Key))
{
    char key = item.Key;
    int count = item.Value;
    Console.WriteLine(key.ToString() + " : " + count.ToString());
}

注意:这只会对罗马字母(A,B等)按字母顺序排序。

注2:如果文件不存在,您可能需要在文件顶部添加using System.Linq;

Try it online

结果:

O : 3
B : 1
M : 1