views:

824

answers:

1

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
+6  A: 

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);
Rotsor
Thanks a lot for your elaboration! So in C#, `pair => pair.Key` is of type `Func`? How do you declare one of those? (So that one could do `sortedDict.ToDictionary(funcKey, funcVal);`?)
Kache4
`Func<KeyValuePair<string, int>, int> funcKey = pair => pair.Key;``Func<KeyValuePair<string, int>, string> funcVal = pair => pair.Value;`Lambda expression `pair => pair.Key` by itself doesn't have any type. Its type is determined only when you cast it to something (Delegate type, such as Func<...>, or Expression, which is quite a different thing).
Rotsor
Actually, I'd suggest you not use C# LINQ syntax because it kind of hides from you what methods you really call, and looks alien for C# language. I never use it because I think it's ugly.Your sample could be written in C# without linq like this: `sortedDict = itemCounter.OrderByDescending(entry => entry.Value)`. Not longer, right?
Rotsor
I don't see a `OrderByDescending` method for `Dictionary`.
Kache4