Use LINQ Intersect method to find common items in two collections in .NET

C# Tip 💡 ->
Did you know LINQ Intersect can be used to find common items between two collections in .NET? Simple example below …

Using LINQ Intersect with custom reference types in .NET

Remember to implement a custom equality comparer for your own reference types if you want comparisons done based on value rather than by reference which is the default.

In the below example, we deem products to be equal if they have the same Id …

… and we can now pass that comparer into the Intersect method

The intersect IEnumerable will now contain Banana and Cherry.

What do you think?
Do you use Intersect much?

Leave a Reply

Your email address will not be published. Required fields are marked *