Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - convert an ILookup into another ILookup

This should be simple, but I can't think of a good way to do it. How do you transform an ILookup into another ILookup? For example, how would you copy/clone an ILookup, producing another ILookup with the same keys and same groups?

Here's my lame attempt:

static ILookup<TKey, TValue> Copy<TKey, TValue>(ILookup<TKey, TValue> lookup)
{
    return lookup
        .ToDictionary(
            grouping => grouping.Key,
            grouping => grouping.ToArray())
        .SelectMany(pair =>
            pair
                .Value
                .Select(value =>
                    new KeyValuePair<TKey, TValue>(pair.Key, value)))
        .ToLookup(pair => pair.Key, pair => pair.Value);
}

Can anyone improve this?

-- Brian

like image 706
Brian Berns Avatar asked Dec 01 '25 17:12

Brian Berns


1 Answers

How about this:

return lookup
  .SelectMany (grp => grp, (grp, item) => new { grp.Key, item})
  .ToLookup (x => x.Key, x => x.item);
like image 85
Joe Albahari Avatar answered Dec 05 '25 00:12

Joe Albahari