Intersect Method

Namespace: System.Linq
Assembly: System.Linq.dll
public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)

Returns the set intersection of two sequences.

Parameters

first: IEnumerable<TSource>

The first sequence to compare.

second: IEnumerable<TSource>

The second sequence to compare.

Return Value

IEnumerable<TSource>: A sequence that contains the elements that are present in both sequences.

Remarks

The Intersect method returns only the unique values in the common elements between the two sequences. It uses the default equality comparer to compare values.

If the two sequences contain duplicate elements, the resulting sequence will contain only one instance of each common element.

Example


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List<int> numbers1 = new List<int> { 5, 2, 3, 9, 4, 1 };
        List<int> numbers2 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };

        IEnumerable<int> intersection = numbers1.Intersect(numbers2);

        Console.WriteLine("Common elements:");
        foreach (int number in intersection)
        {
            Console.WriteLine(number);
        }
        // Output:
        // Common elements:
        // 5
        // 2
        // 3
        // 9
        // 4
        // 1
    }
}