CSharp - Use custom Comparer with ToLookup operator

Introduction

By using the custom equality comparison object we can handle string with leading zeros.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w w w . ja  va  2  s  .com
{
    static void Main(string[] args)
    {
        ILookup<string, Actor2> lookup = Actor2.GetActors()
          .ToLookup(k => k.birthYear, new MyStringifiedNumberComparer());

        //  Let's see if we can find the 'one' born in 1964.
        IEnumerable<Actor2> actors = lookup["0001964"];
        foreach (var actor in actors)
            Console.WriteLine("{0} {1}", actor.firstName, actor.lastName);
    }
}
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();
    }
}
public class Actor2
{
    public string birthYear;
    public string firstName;
    public string lastName;
    public static Actor2[] GetActors()
    {
        Actor2[] actors = new Actor2[] {
      new Actor2 { birthYear = "1964", firstName = "Kotlin", lastName = "Ruby" },
      new Actor2 { birthYear = "1968", firstName = "Owen", lastName = "Windows" },
      new Actor2 { birthYear = "1960", firstName = "Javascript", lastName = "Spader" },
      //  The world's first Y10K-compliant date!
      new Actor2 { birthYear = "01964", firstName = "Scala",
        lastName = "Java" },
    };

        return (actors);
    }
}

Result

Related Topic