Question

I have a List of List<Foo>. I am trying to make two new collections of List<Foo> that contains the similarities and differences. I have read a lot of posts on this site, most deal with single Lists while I am dealing with a collection of multiple, below is my solution:

List<List<Foo>> listOfLists = [Build up the list, not important]

HashSet<Foo> same = listOfLists
.Skip(1)
.Aggregate(
new HashSet<Foo>(listOfLists.First()),
(h, e) =>
{
h.IntersectWith(e);
return h;
}
);

HashSet<Foo> diff = listOfLists
.Skip(1)
.Aggregate(
new HashSet<Foo>(listOfLists.First()),
(h, e) =>
{
h.ExceptWith(e);
return h;
}
);

However on the diff method, it seems to only return the different Foo collections from the second List<Foo> in the ListsofLists collection.

Was it helpful?

Solution

I think the easiest way to calculate the diff in your case would be to calculate all the elements first and then remove the common ones (already calculated):

HashSet<Foo> all = listOfLists
    .Skip(1)
    .Aggregate(
        new HashSet<Foo>(listOfLists.First()),
        (h, e) =>
        {
            h.UnionWith(e);
            return h;
        }
    );

HashSet<Foo> diff = all.ExceptWith(same)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top