Search code examples
c#performancelinqintersect

Items with both properties contained in a list


I have a list of objects X (with the name x) with properties a and b of the same type Location. I also have a list of locations y. I need to find all objects in x for which a AND b are contained in the list y.

I can do it with loops and Wheres but as both lists are huge, I need a really good performing solution. Is there any way to use Intersect in this case? Or something else?

Here some pseudo code

class X
{
    Location a;
    Location b;
}

GetMatches(List<X> x, List<Location> y) { ?? }

Solution

  • First convert the y list to a HashSet.

    var yHashSet = y.ToHashSet();
    

    Then getting the matches is fast and easy:

    private static List<X> GetMatches(List<X> x, HashSet<Location> y)
    {
        return x
            .Where(item => y.Contains(item.a) && y.Contains(item.b))
            .ToList();
    }
    

    Make it parallel to become even faster:

    private static List<X> GetMatchesParallel(List<X> x, HashSet<Location> y)
    {
        return x
            .AsParallel()
            .AsOrdered()
            .Where(item => y.Contains(item.a) && y.Contains(item.b))
            .ToList();
    }