C# Enumerable Contains(IEnumerable, TSource, IEqualityComparer)
Description
Determines
whether a sequence contains a specified element by using a specified IEqualityComparer
Syntax
public static bool Contains<TSource>(
this IEnumerable<TSource> source,
TSource value,//from ww w . j a v a 2 s. co m
IEqualityComparer<TSource> comparer
)
Parameters
TSource
- The type of the elements of source.source
- A sequence in which to locate a value.value
- The value to locate in the sequence.comparer
- An equality comparer to compare values.
Returns
returns true if the source sequence contains an element that has the specified value; otherwise, false.
Example
The following example shows how to implement an equality comparer that can be used in the Contains method.
/*from w w w .j av a 2 s. c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
Product[] fruits = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "lemon", Code = 12 } };
Product apple = new Product { Name = "apple", Code = 9 };
Product kiwi = new Product {Name = "kiwi", Code = 8 };
ProductComparer prodc = new ProductComparer();
bool hasApple = fruits.Contains(apple, prodc);
bool hasKiwi = fruits.Contains(kiwi, prodc);
Console.WriteLine("Apple? " + hasApple);
Console.WriteLine("Kiwi? " + hasKiwi);
}
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
class ProductComparer : IEqualityComparer<Product>
{
public Boolean Equals(Product x, Product y){
return x.Code == y.Code;
}
public int GetHashCode(Product product)
{
int hashProductCode = product.Code.GetHashCode();
return hashProductCode;
}
}
The code above generates the following result.