CSharp - Use custom Comparer with Contains operator

Description

Use custom Comparer with Contains operator

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w  w  w  .j  av a  2s  .  c  om
{
    static void Main(string[] args)
    {
        string[] stringifiedNums = { "001", "49", "017", "0080", "00027", "2" };

        bool contains = stringifiedNums.Contains("0000002", new MyStringifiedNumberComparer());

        Console.WriteLine(contains);

        contains = stringifiedNums.Contains("000271", new MyStringifiedNumberComparer());

        Console.WriteLine(contains);
    }
}
public class MyStringifiedNumberComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return (Int32.Parse(x) == Int32.Parse(y));
    }

    public int GetHashCode(string obj)
    {
        return Int32.Parse(obj).ToString().GetHashCode();
    }
}

Result

Related Topic