Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to get shared items in a sublist

I have a class that has a property which is a List, I will name this class A. Then I have a List<A>.

I need a LINQ for objects to get all the objects B that are present on ALL the items on the List<A>.

Example to clarify:

var list = new List<A>
           {
             new A { B = new List<B> { B1, B2, B3, B4 } }
             new A { B = new List<B> { B3, B4, B5, B6 } }
             new A { B = new List<B> { B2, B3, B4, B5, B6 } }
           };

The query must return the objects B3 and B4 because are the only ones contained on all the List<A> objects.

like image 495
Ignacio Soler Garcia Avatar asked Jan 16 '12 22:01

Ignacio Soler Garcia


1 Answers

If you have a list of lists and you want the elements that are in all the inner lists, you can use a combination of Aggregate and Intersect, like this:

IEnumerable<IEnumerable<string>> listOfLists = new string[][] {
    new string[] { "B1", "B2", "B3", "B4" },
    new string[] { "B3", "B4", "B5", "B6" },
    new string[] { "B2", "B3", "B4", "B5", "B6" }
};

IEnumerable<string> commonElements = listOfLists.Aggregate(Enumerable.Intersect);
like image 133
Matthew Strawbridge Avatar answered Sep 19 '22 16:09

Matthew Strawbridge