C# Enumerable Union(IEnumerable, IEnumerable, IEqualityComparer)
Description
Produces
the set union of two sequences by using a specified IEqualityComparer
Syntax
public static IEnumerable<TSource> Union<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,//from www . j a v a 2s .c o m
IEqualityComparer<TSource> comparer
)
Parameters
TSource
- The type of the elements of the input sequences.first
- An IEnumerablewhose distinct elements form the first set for the union. second
- An IEnumerablewhose distinct elements form the second set for the union. comparer
- The IEqualityComparerto compare values.
Example
The following example shows how to implement an equality comparer that can be used in the Union method.
/*from www . j a v a 2 s . com*/
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> union =
store1.Union(store2, new ProductComparer());
foreach (var product in union)
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.Name.GetHashCode();
}
}
The code above generates the following result.