...

/

Intersect, Union, and Except Methods

Intersect, Union, and Except Methods

Learn how to find the intersection, union, and difference between two collections.

How to find the intersection between two collections

The Intersect method finds the common elements between two collections.

Let’s find the movies we both have watched and rated in our catalogs.

Press + to interact
using System;
using System.Collections.Generic;
using System.Linq;
namespace MovieCatalog
{
internal class Program
{
public static void Main(string[] args)
{
var mine = new List<Movie>
{
new Movie("Terminator 2", 1991, 4.7f),
// ^^^^^^^^^^^^^^
new Movie("Titanic", 1998, 4.5f),
new Movie("The Fifth Element", 1997, 4.6f),
new Movie("My Neighbor Totoro", 1988, 5f)
// ^^^^^^^^^^^^^^^^^^^^
};
var yours = new List<Movie>
{
new Movie("My Neighbor Totoro", 1988, 5f),
// ^^^^^^^^^^^^^^^^^^^^
new Movie("Pulp Fiction", 1994, 4.3f),
new Movie("Forrest Gump", 1994, 4.3f),
new Movie("Terminator 2", 1991, 5f)
// ^^^^^^^^^^^^^^
};
var weBothHaveSeen = mine.Select(m => m.Name)
.Intersect(yours.Select(m => m.Name));
Console.WriteLine("We both have seen:");
PrintMovieNames(weBothHaveSeen);
}
private static void PrintMovieNames(IEnumerable<string> names)
{
Console.WriteLine(string.Join(",", names));
}
}
internal class Movie
{
public Movie(string name, int releaseYear, float rating)
{
Name = name;
ReleaseYear = releaseYear;
Rating = rating;
}
public string Name { get; set; }
public int ReleaseYear { get; set; }
public float Rating { get; set; }
}
}

Notice that, this time, we have two lists of movies, mine and yours, with the ones I’ve watched and the ones I guess you have watched, respectively.

To find the movies we both have seen (the ...