Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

how about

var commonElements = listA.Intersect(listB).ToList();

You could try using the Enumerable.Intersect function, which takes two lists and turns them into one which has all the elements that are in both lists. There is also an overload that takes an IEqualityComparer<T> if you want the equality of the objects not to be based on reference equality/default IEqualityComparer<T> for your class.

Here's how you'd use it:

var commonElements = listA.Intersect(listB); 
//you can add an IEqualityComparer<T> to the arguments,
//or append .ToList()/.ToArray to make it a list/array.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top