D.R.
D.R.

Reputation: 21194

Why is Dictionary.ToLookup() not working?

I have a Dictionary<TType, List<TData>> which represents some kind of internal data container. TData elements are grouped by TType.

A user may query my dictionary and should be given an ILookup<TType, TData> as result. The simplest query is to return the whole data container:

public ILookup<TType, TData> QueryEverything ()
{
    return _data.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
}

However, that does not work. Why? Isn't a lookup nothing more than a dictionary of Key => IEnumerable<Value>?

Upvotes: 2

Views: 410

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

You could Try this:

public ILookup<TType, TData> QueryEverything ()
{
    return _data.SelectMany(kvp => p.Value.Select(x => new { kvp.Key, Value = x }))
                .ToLookup(kvp => kvp.Key, kvp => kvp.Value);
}

Of course, instead of an anonymous type, you could create KeyValuePair<TType, TData> or a Tuple<TType, TData> just as easily.

Or perhaps a better solution (if you can manage to refactor your code) is to change your private _data dictionary to an ILookup<TType, TData>, so there is no need to convert the dictionary in the first place.

Upvotes: 1

Related Questions