C# Enumerable Intersect(IEnumerable, IEnumerable)

Description

Produces the set intersection of two sequences by using the default equality comparer to compare values.

Syntax


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

Parameters

  • TSource - The type of the elements of the input sequences.
  • first - An IEnumerable whose distinct elements that also appear in second will be returned.
  • second - An IEnumerable whose distinct elements that also appear in the first sequence will be returned.

Example

The following code example demonstrates how to use Intersect to return the elements that appear in each of two sequences of integers.


//from  www. j  a  v a 2s.  c om
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
     int[] id1 = { 44, 26, 92, 30, 71, 38 };
     int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

     IEnumerable<int> both = id1.Intersect(id2);

     foreach (int id in both)
         Console.WriteLine(id);


     ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
                            new ProductA { Name = "orange", Code = 4 } };
     
     ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
                            new ProductA { Name = "lemon", Code = 12 } };
     
     IEnumerable<ProductA> duplicates = store1.Intersect(store2);
     
     foreach (var product in duplicates)
         Console.WriteLine(product.Name + " " + product.Code);
  }
}

public class ProductA
{ 
    public string Name { get; set; }
    public int Code { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{

    public bool Equals(ProductA x, ProductA y)
    {
        return x.Name.Equals(y.Name);
    }

    public int GetHashCode(ProductA obj)
    {
        return obj.Name.GetHashCode();
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable