// 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>)'
有一些无效的参数
是否简化了将list/enumberable转换KeyValuePair<T, U>
为Dictionary<T, U>
?
Linq转换,.ToDictionary()扩展无效.
已经在同一个网站上阅读了一篇关于这个帖子但没有用的帖子,我感觉有点难过,但我确信我之前已经这样做了.
我有一本词典.我想从Dictionary中获取前200个值.
Dictionary<int,SomeObject> oldDict = new Dictionary<int,SomeObject>();
//oldDict gets populated somewhere else.
Dictionary<int,SomeObject> newDict = new Dictionary<int,SomeObject>();
newDict = oldDict.Take(200).ToDictionary();
Run Code Online (Sandbox Code Playgroud)
显然,take返回一个IENumerable,所以你必须运行ToDictionary()将它转换回相同类型的字典.但是,它只是不起作用,它想要一些随机的键选择器 - 或者什么?我甚至尝试过施展,但无济于事.有任何想法吗?
如果您在stackoverflow中转到此链接。关于将“可加密的”转换为“字典”存在一个问题。所以我的问题是,当我们拥有字典对象时,为什么我们需要IEnumerable?
实际上,我正在尝试找出它们之间的区别。