2010-06-17 88 views
35

我是继answer to another question,和我:转换的IOrderedEnumerable <KeyValuePair <string, int>>成字典<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>>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments

回答

47

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

这是正确的:

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

与短版之中:

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

非常感谢您的阐述!所以在C#中,'pair => pair.Key'的类型是'Func'?你如何申报其中之一? (所以,我可以做'sortedDict.ToDictionary(funcKey,funcVal);'?) – Kache 2010-06-17 23:31:18

+3

其实,我建议你不要使用C#LINQ语法,因为它会隐藏你真正调用的方法,并且看起来对于C#语言。我从不使用它,因为我觉得它很丑。 您的示例可以用C#编写,而不需要像这样的linq:'sortedDict = itemCounter.OrderByDescending(entry => entry.Value)'。不再是吧? – Rotsor 2010-06-17 23:43:07

+2

我没有看到'Dictionary'的'OrderByDescending'方法。 – Kache 2010-06-21 14:26:31

8

我相信这样做既在一起的最清晰的方式:排序字典和将其转换回字典会:

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

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

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