我是繼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
非常感謝您的闡述!所以在C#中,'pair => pair.Key'的類型是'Func'?你如何申報其中之一? (所以,我可以做'sortedDict.ToDictionary(funcKey,funcVal);'?) – Kache 2010-06-17 23:31:18
其實,我建議你不要使用C#LINQ語法,因爲它會隱藏你真正調用的方法,並且看起來對於C#語言。我從不使用它,因爲我覺得它很醜。 您的示例可以用C#編寫,而不需要像這樣的linq:'sortedDict = itemCounter.OrderByDescending(entry => entry.Value)'。不再是吧? – Rotsor 2010-06-17 23:43:07
我沒有看到'Dictionary'的'OrderByDescending'方法。 – Kache 2010-06-21 14:26:31