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

為{幸葍}努か 提交于 2019-12-03 09:21:45

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

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

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