linqlambdaigroupingilookup

LINQ Convert from IGrouping to Lookup


I have two variables of type ILookup. I wanted to use Union or Concat to combine their values and assign the result to a third variable of the same type. Both Union and Concat return IGrouping. It must be dead simple to convert IGrouping to the ILookup but I just can't do it!!! :-( IGrouping exposes just the Key so I am struggling with the second parameter of the Lookup.... Any help will be much, much appreciated.


Solution

  • I think you'll need to flatten the sequences first, to use ToLookup:

    var lookup = first.Concat(second)
                      .SelectMany(group => group,
                                  (group, item) => new { Key = group.Key, 
                                                         Item = item })
                      .ToLookup(x => x.Key, x => x.Item);
    

    That uses the form of SelectMany which takes two delegates: one to convert an item in the original sequence to a collection, and another to take an item in the original collection (i.e. the group) and an item in the returned collection (i.e. the items matching that group's key) to get to the result item. This is the simplest way (I think!) of flattening a grouping into a sequence of items with their keys.

    The above isn't tested, so could be completely wrong. It's also relatively inefficient... it's a shame that there's no way of building an instance of Lookup directly. You could implement ILookup yourself, of course.