0

I have a set of collections that look like this:

var arr1 = new string[] { "cat", "dog", "monkey", "chicken" };
var arr2 = new string[] { "chicken", "bird", "dog" };
var arr3 = new string[] { "dog", "camel", "chimp", "turtle", "chicken" };
var arr4 = new string[] { "dog", "chicken" };
var arr5 = new string[] { "camel", "dog", "chicken" };

And what I need to do is come up with some LINQ query to find all items common among all collections. Using the above data set, how would I derive this result:

var result = new string[] { "chicken", "dog" };

Since chicken and dog exists in all collections, they should be the only things in the resultant collection.

Doesn't have to be arrays, just any generic collection type.

This seems like a common query, so this post may be a duplicate... it's really hard to search for these types of queries since there are many derivatives.

Thank you

Andy
  • 10,110
  • 3
  • 28
  • 47
  • 1
    thanks @Servy -- that was fast :) – Andy Nov 08 '18 at 14:09
  • AddRange() and then distinct() :D – Hassaan Nov 08 '18 at 14:10
  • @HassaanKhan That would union all of the sequences, not intersect them. Also, if you did want to union all of them, adding them all to a set would accomplish that with a lot less memory as your total memory footprint is only the size of the output, not the size of all of the items in all of the sequences added together. – Servy Nov 08 '18 at 14:14
  • The accepted answer on the @Servy reference link works great for me. – Andy Nov 08 '18 at 14:18
  • 1
    @Andy You should not use the accepted answer. Use Jon's. The accepted answer violates a number of good practices. – Servy Nov 08 '18 at 14:24
  • Got it, @Servy... Jon's is way easier to read and understand. Thanks agian – Andy Nov 08 '18 at 15:19

0 Answers0