Home
C#
Intersect Example
Updated Nov 30, 2021
Dot Net Perls
Intersect. This is an extension method from the System.Linq namespace. In set theory, an intersection is the subset of each collection that is found in both collections.
Extension
HashSet
SortedSet
C# method details. Intersect gets common elements from 2 collections. The Intersect method here is elegant—it can be used on many types of elements.
This program invokes the Intersect method. The two using directives at the top of the program specify where the types are located. We use the array initializer syntax.
Array Initialize
Note Each array has three numbers in it. Both arrays have the numbers 2 and 3, and one other number.
Result The results show that the Intersect method returns these exact numbers: 2 and 3. These are the intersecting numbers.
Array
Tip Intersect here compares elements in the default way for their type. For ints, a simple numeric comparison for equality is done.
int
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Assign two arrays.
        int[] array1 = { 1, 2, 3 };
        int[] array2 = { 2, 3, 4 };
        // Call Intersect extension method.
        var intersect = array1.Intersect(array2);
        // Write intersection to screen.
        foreach (int value in intersect)
        {
            Console.WriteLine(value);
        }
    }
}
2 3
A summary. We examined the Intersect method. We computed the intersecting part of two integer arrays using a declarative syntax, rather than an imperative loop construct.
A final tip. A declarative syntax is more concise. But an imperative style could improve the efficiency of this particular operation.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 30, 2021 (simplify).
Home
Changes
© 2007-2025 Sam Allen