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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With