Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T>.ToLookup<TKey, TValue>

I am trying to turn an IEnumerable<KeyValuePair<string, object>> into an ILookup<string, object> using the following code:

var list = new List<KeyValuePair<string, object>>()
{
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("London", null),
    new KeyValuePair<string, object>("Sydney", null)
};

var lookup = list.ToLookup<string, object>(a => a.Key);

But the compiler is complaining with:

Instance argument: cannot convert from 'System.Collections.Generic.List>' to 'System.Collections.Generic.IEnumerable'

and

'System.Collections.Generic.List>' does not contain a definition for 'ToLookup' and the best extension method overload 'System.Linq.Enumerable.ToLookup(System.Collections.Generic.IEnumerable, System.Func)' has some invalid arguments

and

cannot convert from 'lambda expression' to 'System.Func'

What am I doing wrong with the lambda expression?

like image 892
Darbio Avatar asked Mar 08 '26 22:03

Darbio


1 Answers

Just remove <string, object> for the types to be inferred automatically:

var lookup = list.ToLookup(a => a.Key);

As it really should be:

var lookup = list.ToLookup<KeyValuePair<string, object>, string>(a => a.Key);
like image 78
horgh Avatar answered Mar 10 '26 10:03

horgh