tags:

views:

35

answers:

1

Let's say I have 4 arrays:

[1,3,54,4]
[54,2,3,9]
[3,2,9,54]
[54,8,4,3]

I need to get the objects (in this case integers but they will be custom object) that are present in (common to) all of the arrays. In the case above I would need the result to be: [54,3] as those are the only items two that are in all four arrays. Order does not matter, speed matters greatly, array sizes and the number of arrays will vary greatly. I'm using C# 4 and ASP.NET. The arrays will be List although they could just be converted.

Thanks :)

+6  A: 

How about:

ISet<int> intersection = new HashSet<int>(firstArray);
intersection.IntersectWith(secondArray);
intersection.IntersectWith(thirdArray);
intersection.IntersectWith(fourthArray);

Note that this should be more efficient than the more obvious:

var x = firstArray.Intersect(secondArray)
                  .Intersect(thirdArray)
                  .Intersect(fourthArray);

as the latter will create a new hash set for each method call.

Obviously with multiple arrays you'd just loop, e.g.

static ISet<T> IntersectAll<T>(IEnumerable<IEnumerable<T>> collections)
{
    using (IEnumerator<T> iterator = collections.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            return new HashSet<T>();
        }
        HashSet<T> items = new HashSet<T>(iterator.Current);
        while (iterator.MoveNext())
        {
            items.IntersectWith(iterator.Current);
        }
        return items;
    }
}
Jon Skeet
EDIT:Thanks for the fast answer! Look exactly what I want. Thanks for the effort, and creating the last example :)
Matt