CSharp - Use custom Comparer and map element to different type in ToDictionary operator

Description

Use custom Comparer and map element to different type in ToDictionary operator

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from w  ww  .  j  a  v  a 2 s . c om*/
{
    static void Main(string[] args)
    {
        Dictionary<string, string> eDictionary = Student2.GetStudentsArray()
          .ToDictionary(k => k.id,                           //  keySelector
                        i => string.Format("{0} {1}",        //  elementSelector
                          i.firstName, i.lastName),
                        new MyStringifiedNumberComparer());  //  comparer

        string name = eDictionary["2"];
        Console.WriteLine("Student whose id == \"2\" : {0}", name);

        name = eDictionary["000002"];
        Console.WriteLine("Student whose id == \"000002\" : {0}", name);
    }
}
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 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