返回按值排序的ReadOnlyDictionary

时间:2015-01-11 23:20:15

标签: c# linq dictionary

我有一个包含Dictionary<string, uint>的方法。该方法返回从ReadOnlyDictionary<string, uint>创建的Dictionary<string, uint>

我希望将返回的字典按 value 排序,而不是按键排序。我搜索了互联网,发现了一些按价值排序的LINQ:

var sorted = from entry in _wordDictionary orderby entry.Value descending select entry;

但是,我不知道如何将其与我返回的ReadOnlyDictionary<string, uint>结合使用。

这是我的代码:

public static ReadOnlyDictionary<string, uint> GetWordCountDictionary(string stringToCount)
{
    Dictionary<string, uint> wordDictionary = new Dictionary<string, uint>();

    //Rest of the method here that is not relevant

    var sorted = from entry in wordDictionary orderby entry.Value descending select entry;

    ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(wordDictionary);

    return result;
}

正如代码当前所示,这将返回未排序的字典,但是,如果我改为:

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted);

我收到了错误:

The best overloaded method match for 'System.Collections.ObjectModel.ReadOnlyDictionary<string,uint>.ReadOnlyDictionary(System.Collections.Generic.IDictionary<string,uint>)' has some invalid arguments

Argument 1: cannot convert from 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<string,uint>>' to 'System.Collections.Generic.IDictionary<string,uint>'

如何返回按值排序的字典?

修改

如果它是相关的,这就是我目前能够迭代结果的方式:

var result = WordCounter.GetWordCountDictionary(myString);

foreach (var word in result)
{
    Console.WriteLine ("{0} - {1}", word.Key, word.Value);
}

3 个答案:

答案 0 :(得分:1)

构造函数期望IDictionary<string,uint>,但您正在给它IOrderedEnumerable<KeyValuePair<string,uint>>

var result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(x => x.Key,x => x.Value));

答案 1 :(得分:1)

因为您要将排序后的结果放入字典中,所以根据MSDN确定枚举期间返回项目的顺序:

  

出于枚举的目的,字典中的每个项都被视为   表示值及其值的KeyValuePair结构   键。返回项目的顺序未定义。

我建议您在列表中返回结果:

        var sorted = (from entry in wordDictionary
                     orderby entry.Value descending
                     select entry).ToList();

        foreach (var word in sorted)
        {
            Console.WriteLine("{0} - {1}", word.Key, word.Value);
        }

ToList方法会产生System.Collections.Generic.List<KeyValuePair<string, uint>>

答案 2 :(得分:0)

您的问题的解决方法是更改​​行

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted);

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(t => t.Key,t => t.Value));