2

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>?

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • Looks like the element selector (`kvp.Value`) should create a single element and not the whole `IEnumerable`. Is there no other overload / utility method which allows me to fill in the whole `IEnumerable`? – D.R. Oct 06 '13 at 20:47
  • See http://stackoverflow.com/questions/10420228/how-do-i-convert-a-dictionary-to-a-lookup – Mike Zboray Oct 06 '13 at 20:57

1 Answers1

1

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • ILookup is immutable, however, my container is not. Looks like your solution is the only possible one (just found the same code also in another SO thread). This really should be part of LINQ out-of-the-box... – D.R. Oct 06 '13 at 20:51
  • You might also try creating your own collection which implements `ILookup` but is also mutable. – p.s.w.g Oct 06 '13 at 20:53