2010-06-17 225 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); 
相關問題