Search code examples
c#linqlistwhere-in

which is more efficient to select the elements taht are common in two list?


If I have two list and I want to create a new third list that has only the common elements in the two list (a where in query) can use this code:

var listC = listB.Join(listA, b => b.ObjectAId, a => a.Id, (b, a) => b).ToList();

This way has an O(n) complexity.

However, I also can use a select method in this way:

var lstC = listA.Where(r => listB.Contains(r).ToList();

This second way is O(n) too?

If the two ways has the same efficient, which differences are between both of them?

Thanks.


Solution

  • var listC = listA.Intersect(listB); // perhaps a .ToList() on the end
    

    This will use hashing to keep it as cheap as possible.