转换IOrderedEnumerable <keyvaluepair <string,int =“”>&gt; into Dictionary <string,int =“”> </string,> </keyvaluepair <string,>

时间:2010-06-17 22:46:53

标签: c# linq todictionary

我跟着answer to another question,我得到了:

// 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>)'有一些无效的参数

3 个答案:

答案 0 :(得分:52)

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

这是正确的:

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

短版本:

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

答案 1 :(得分:9)

我相信最简洁的方法是:将字典排序并将其转换回字典:

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

答案 2 :(得分:0)

这个问题太旧了,但仍想提供答案供参考:

itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
相关问题