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

那年仲夏 提交于 2019-12-04 15:01:18

问题


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


回答1:


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);



回答2:


I believe the cleanest way of doing both together: sorting the dictionary and converting it back to a dictionary would be:

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



回答3:


The question is too old but still would like to give answer for reference:

itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);


来源:https://stackoverflow.com/questions/3066182/convert-an-iorderedenumerablekeyvaluepairstring-int-into-a-dictionarystrin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!