C# Enumerable Intersect(IEnumerable, IEnumerable, IEqualityComparer)
Description
Produces
the set intersection of two sequences by using the specified IEqualityComparer
Syntax
public static IEnumerable<TSource> Intersect<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,/*from ww w .j a v a2s.c o m*/
IEqualityComparer<TSource> comparer
)
Parameters
TSource
- The type of the elements of the input sequences.first
- An IEnumerablewhose distinct elements that also appear in second will be returned. second
- An IEnumerablewhose distinct elements that also appear in the first sequence will be returned. comparer
- An IEqualityComparerto compare values.
Example
The following example shows how to implement an equality comparer that can be used in the Intersect method.
//from w ww. ja va 2 s . c o m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
Product[] store1 = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 } };
Product[] store2 = { new Product { Name = "apple", Code = 9 },
new Product { Name = "lemon", Code = 12 } };
IEnumerable<Product> duplicates =
store1.Intersect(store2, new ProductComparer());
foreach (var product in duplicates)
Console.WriteLine(product.Name + " " + product.Code);
}
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
return x.Name == y.Name;
}
public int GetHashCode(Product product)
{
return product.Code.GetHashCode();
}
}
The code above generates the following result.