Convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

I was following the answer to another question, and I got:

// 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's asking for a parameter Func<string, int> keySelector . I tried following a few semi-relevant examples I've found online and put in k => k.Key , but that gives a compiler error:

'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


You are specifying incorrect generic arguments. You are saying that TSource is string, when in reality it is a KeyValuePair.

This one is correct:

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

with short version being:

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

我相信将两者结合在一起的最简洁的方法是:对字典进行排序并将其转换回字典:

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

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

itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
链接地址: http://www.djcxy.com/p/70786.html

上一篇: 在列表中查找单个数字

下一篇: 将IOrderedEnumerable <KeyValuePair <string,int >>转换为Dictionary <string,int>