CSharp - Use custom Comparer with ToLookup operator and return different type of LookUp

Introduction

Lookup returned is using a key value different from either of the values retrieved using that key.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w  w w .j  av a 2  s . c o  m
{
    static void Main(string[] args)
    {
        ILookup<string, string> lookup = Actor2.GetActors()
          .ToLookup(k => k.birthYear,
                    a => string.Format("{0} {1}", a.firstName, a.lastName),
                    new MyStringifiedNumberComparer());

        //  Let's see if we can find the 'one' born in 1964.
        IEnumerable<string> actors = lookup["0001964"];
        foreach (var actor in actors)
            Console.WriteLine("{0}", actor);
    }
}
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