myWallJSON myWallJSON - 10 days ago 6
C# Question

How to get a Lookup as Union of 2 old Lookups?

How can you get a Lookup from a Union of 2 old Lookups? Seems like

a = a.Union(b)
does not work for them.

Answer

If you have the original lists that the lookups came from, it might be easier. It might also be easier if you used Dictionarys of Lists instead of lookups. However, it's still possible to merge two lookup objects into a new object. The basic idea is to retrieve the original values from the lookups, and then create a new lookup from the concatenated set of both.

var a = new[] {"apple","aardvark","barn"};
var b = new[] {"baboon", "candy", "cork"};

var al = a.ToLookup (x => x[0]);
var bl = b.ToLookup (x => x[0]);

var cl = al.Concat(bl).SelectMany(x => x).ToLookup(x => x[0]);

If you also don't know the original key selector function, you can use this variant.

var cl = al.Concat(bl)
    .SelectMany(lookup => lookup.Select(value => new { lookup.Key, value}))
    .ToLookup(x => x.Key, x => x.value);
Comments