CSharp - LINQ Intersect

Introduction

The Intersect operator returns the set intersection of two source sequences.

Prototypes

public static IEnumerable<T> Intersect<T>(
        this IEnumerable<T> first,
        IEnumerable<T> second);

Exceptions

ArgumentNullException is thrown if any arguments are null.

The following code shows how to use Intersect operator.

It uses Take and Skip operators to generate two sequences and get some overlap.

When we call the Intersect operator on those two generated sequences, only the duplicated element should be in the returned intersect sequence.

We will display the counts of the codeNames array and all the sequences.

Lastly, we will enumerate through the intersect sequence displaying each element.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from   www .j  a  v a 2 s  .c o  m*/
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<string> first = codeNames.Take(5);
        IEnumerable<string> second = codeNames.Skip(4);
        
        IEnumerable<string> intersect = first.Intersect(second);
        
        Console.WriteLine("The count of the codeNames array is: " + codeNames.Count());
        Console.WriteLine("The count of the first sequence is: " + first.Count());
        Console.WriteLine("The count of the second sequence is: " + second.Count());
        Console.WriteLine("The count of the intersect sequence is: " + intersect.Count());
        
        foreach (string name in intersect)
          Console.WriteLine(name);
    }
}

Result