将IOrderedEnumerable <KeyValuePair <string,int >>转换为Dictionary <string,int>

我正在回答另一个问题,我得到了:

// 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<string, int> keySelector 。 我尝试了以下几个我在网上找到的半相关示例,并将其放入k => k.Key ,但这给出了一个编译器错误:

'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>'不包含'ToDictionary'的定义和最佳扩展方法重载'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)'有一些无效参数


您正在指定不正确的泛型参数。 你说TSource是字符串,实际上它是一个KeyValuePair。

这是正确的:

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

短版本是:

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

我相信将两者结合在一起的最简洁的方法是:对字典进行排序并将其转换回字典:

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

这个问题太旧了,但仍然想回答参考:

itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
链接地址: http://www.djcxy.com/p/70785.html

上一篇: Convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

下一篇: How to sort list with dictionary?