关于C#:将IOrderedEnumerable >转换为Dictionary

Convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

我在跟踪另一个问题的答案,我得到:

1
2
3
4
5
6
7
8
// itemCounter is a Dictionary<string, int>, and I only want to keep
// key/value pairs with the top maxAllowed values
if (itemCounter.Count > maxAllowed) {
    IEnumerable<KeyValuePair<string, int>> sortedDict =
        from entry in itemCounter orderby entry.Value descending select entry;
    sortedDict = sortedDict.Take(maxAllowed);
    itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */);
}

Visual Studio正在请求参数Func keySelector。我尝试了以下几个我在网上找到的半相关的例子,并将其放入k => k.Key中,但这给出了一个编译器错误:

'System.Collections.Generic.IEnumerable>'
does not contain a definition for 'ToDictionary' and the best
extension method overload
'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable,
System.Func)'
has some invalid arguments


指定的泛型参数不正确。你是说源是字符串,而实际上它是一个键值对。

这个是正确的:

1
sortedDict.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);

短版本为:

1
sortedDict.ToDictionary(pair => pair.Key, pair => pair.Value);


我相信两种方法结合起来最干净的方法是:对字典进行排序并将其转换回字典:

1
itemCounter = itemCounter.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value);


这个问题太老了,但仍想给出答案供参考:

1
itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);