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

Kac*_*che 37 c# linq todictionary

我正在关注另一个问题答案,我得到了:

// 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? */);
}
Run Code Online (Sandbox Code Playgroud)

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

Rot*_*sor 53

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

这个是正确的:

sortedDict.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)

短版本是:

sortedDict.ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)

  • 实际上,我建议你不要使用C#LINQ语法,因为它隐藏了你真正调用的方法,并且对于C#语言看起来很陌生.我从不使用它,因为我觉得它很难看.您的样本可以使用C#编写而不使用linq:`sortedDict = itemCounter.OrderByDescending(entry => entry.Value)`.不再是吧? (3认同)
  • 我没有看到`Dictionary'的`OrderByDescending`方法. (2认同)

CB0*_*B01 9

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

itemCounter = itemCounter.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
Run Code Online (Sandbox Code Playgroud)