CSharp - Use IEqualityComparer<T> with ToDictionary operator

Description

Use IEqualityComparer<T> with ToDictionary operator

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//www.  ja v a 2  s  .  c o m
{
    static void Main(string[] args)
    {
        Dictionary<string, Student2> eDictionary = Student2.GetStudentsArray()
          .ToDictionary(k => k.id, new MyStringifiedNumberComparer());

        Student2 e = eDictionary["2"];
        Console.WriteLine("Student whose id == \"2\" : {0} {1}",
          e.firstName, e.lastName);

        e = eDictionary["000002"];
        Console.WriteLine("Student whose id == \"000002\" : {0} {1}",
          e.firstName, e.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 Actor
{
    public int birthYear;
    public string firstName;
    public string lastName;

    public static Actor[] GetActors()
    {
        Actor[] actors = new Actor[] {
           new Actor { birthYear = 1964, firstName = "Kotlin", lastName = "Ruby" },
           new Actor { birthYear = 1968, firstName = "Owen", lastName = "Windows" },
           new Actor { birthYear = 1960, firstName = "Javascript", lastName = "Spader" },
           new Actor { birthYear = 1964, firstName = "Scala", lastName = "Java" },
         };

        return (actors);
    }
}
public class Student2
{
    public string id;
    public string firstName;
    public string lastName;
    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student2 { id = "1", firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student2 { id = "2", firstName = "Windows", lastName = "Python" });
        al.Add(new Student2
        {
            id = "3",
            firstName = "Application",
            lastName = "HTML"
        });
        al.Add(new Student2 { id = "4", firstName = "David", lastName = "Visual" });
        al.Add(new Student2 { id = "101", firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student2[] GetStudentsArray()
    {
        return ((Student2[])GetStudentsArrayList().ToArray(typeof(Student2)));
    }
}

Result

Related Topic