示例
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();
}
}
IEquality 接口识别集合的自定义相等比较的实现。也就是说,您可以创建自己的相等定义,并指定此定义与接受IEquality Comparer接口的集合类型一起使用。在.NET Framework中,哈希表、NameValueCollection和OrderedDictionary集合类型的构造函数接受此接口。
日期:2020-04-11 23:03:44 来源:oir作者:oir
