Linq to Dictionary with IEquality Comparer in C#

In this article i am going to explain about linq to dictionary with iequality comparer in c#.
  • 5797

Linq to Dictionary with I Equality Comparer in C#

This interface recognize the implementation of customized equality comparison for collections. That is, you can make your own definition of equality, and specify that this definition be used with a collection type that accepts the IEquality Comparer interface. In the .NET Framework, constructors of the Hashtable, NameValueCollection, and OrderedDictionary collection types accept this interface.

Lets take an example of  Dictionary with I Equality Comparer

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Employee3
{
public string id;
public string firstName;
public string lastName;
public static ArrayList GetEmployeesArrayList()
{
ArrayList al = new ArrayList();
al.Add(new Employee3 { id = "1", firstName = "J", lastName = "R" });
al.Add(new Employee3 { id = "2", firstName = "W", lastName = "G" });
al.Add(new Employee3 { id = "3", firstName = "A", lastName = "H" });
al.Add(new Employee3 { id = "4", firstName = "D", lastName = "L" });
al.Add(new Employee3 { id = "101", firstName = "K", lastName = "F" });
return (al);
}
public static Employee3[] GetEmployeesArray()
{
return ((Employee3[])GetEmployeesArrayList().ToArray(typeof(Employee3)));
}
}
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 MainClass
{
public static void Main()
{
Dictionary<string, string> eDictionary = Employee3.GetEmployeesArray()
.ToDictionary(k => k.id, i => string.Format("{0} {1}", i.firstName, i.lastName), new MyStringifiedNumberComparer());
string name = eDictionary["3"];
Console.WriteLine("Employee whose id == \"3\" : {0}", name);
name = eDictionary["000003"];
Console.WriteLine("Employee whose id == \"000003\" : {0}", name);
Console.ReadKey();
}
}

Output

Clipboard01.jpg

Further Readings

You may also want to read these related articles

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.