C# convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

Posted by Kache4 on Stack Overflow See other posts from Stack Overflow or by Kache4
Published on 2010-06-17T22:46:53Z Indexed on 2010/06/17 22:53 UTC
Read the original article Hit count: 1465

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ