Use the `Intersect` method to find common items in two separate lists

A quick way to compare multiple sets of data.

C#'s intersect method is one of the most popular and efficient ways to find the common elements between two sets of data in C#.

Intersect method

Often you have two different arrays, lists, or other sets of data, and you need to know what items they have in common. Looping through each and comparing individual items works, but it's terribly inefficient and harder to read. This scenario is why LINQ's Intersect method was created. Let's take a look at comparing two sets of strings that represent names of famous developers.

List<string> dotNetDevelopers =
    ["Ada Lovelace", "Katherine Johnson", "Grace Hopper", "Hedy Lamarr", "Barbara Liskov"];
List<string> javaDevelopers =
    ["Ada Lovelace", "Grace Hopper", "Anita Borg", "Barbara Liskov"];

var multiTalentedDevelopers = dotNetDevelopers.Intersect(javaDevelopers);
foreach (var dev in polyglots)
{
    Console.WriteLine(dev);
}

Notice that the loop in this example is done to display the results, not to make the comparison. Intersect returns an IEnumerable<TSource>, so the resulting set is easy to manipulate. Intersect works great with any value type. For another example, let's compare two sets of enums that represent colors:

List<Colors> firstSwatch = [Colors.Blue, Colors.Brown, Colors.Green, Colors.Red, Colors.Yellow];
List<Colors> secondSwatch = [Colors.Blue, Colors.Purple, Colors.Yellow, Colors.Green];

var commonColors = firstSwatch.Intersect(secondSwatch);
foreach (var color in commonColors)
{
    Console.WriteLine(color);
}

The Intersect method uses the default equality comparer for comparison of elements, and that's why it's great for value types. For custom objects, you may have to implement your own IEqualityComparer<T>.


Related Resources

Convert JSON to classes or records
Convert JSON to classes or records
Turn any JSON data you have into a class or record
Params collection in C#
Params collection in C#
Use the params collection in C# so methods can accept a dynamic number of parameters.
File-scoped namespaces and types
File-scoped namespaces and types
Organize code better and reduce bugs by using file-scoped namespaces and objects.