如果键是类的一部分,则使用KeyedCollection。
它是一个字典,其中键派生自对象。
在底层,它是字典。不必在键和值中重复键。
为什么要冒险键与键或值不同?不必在内存中复制相同的信息。
KeyedCollection类
索引器公开组合键
using System.Collections.ObjectModel;
namespace IntIntKeyedCollection
{
class Program
{
static void Main(string[] args)
{
UInt16UInt16O Emp1 = new UInt16UInt16O(34, 1990);
Emp1.PayIDs.Add(1);
Emp1.PayIDs.Add(2);
UInt16UInt16O Emp2 = new UInt16UInt16O(34, 1990, new List<byte>{3,4});
if (Emp1 == Emp2) Console.WriteLine("same");
if (Emp1.Equals(Emp2)) Console.WriteLine("Equals");
Console.WriteLine("Emp1.GetHashCode " + Emp1.GetHashCode().ToString());
UInt16UInt16OCollection Employees = new UInt16UInt16OCollection();
Employees.Add(Emp1);
Employees.Add(new UInt16UInt16O(35, 1991, new List<byte> { 1 } ));
Employees.Add(new UInt16UInt16O(35, 1992, new List<byte> { 1, 2 } ));
Employees.Add(new UInt16UInt16O(36, 1992));
Console.WriteLine(Employees.Count.ToString());
Console.WriteLine(Employees[0].GetHashCode().ToString());
Console.WriteLine(Employees[35, 1991].GetHashCode().ToString());
Console.WriteLine("foreach");
foreach (UInt16UInt16O emp in Employees)
{
Console.WriteLine(string.Format("HashCode {0} EmpID {1} Year {2} NumCodes {3}", emp.GetHashCode(), emp.EmpID, emp.Year, emp.PayIDs.Count.ToString()));
}
Console.WriteLine("sorted");
foreach (UInt16UInt16O emp in Employees.OrderBy(e => e.EmpID).ThenBy(e => e.Year))
{
Console.WriteLine(string.Format("HashCode {0} EmpID {1} Year {2} NumCodes {3}", emp.GetHashCode(), emp.EmpID, emp.Year, emp.PayIDs.Count.ToString()));
}
}
public class UInt16UInt16OCollection : KeyedCollection<UInt16UInt16S, UInt16UInt16O>
{
public UInt16UInt16OCollection() : base(null, 0) { }
protected override UInt16UInt16S GetKeyForItem(UInt16UInt16O item)
{
return item.UInt16UInt16S;
}
public UInt16UInt16O this[UInt16 EmpID, UInt16 Year]
{
get { return this[new UInt16UInt16S(EmpID, Year)]; }
}
}
public struct UInt16UInt16S
{
public readonly UInt16 EmpID, Year;
public UInt16UInt16S(UInt16 empID, UInt16 year) { this.EmpID = empID; this.Year = year; }
}
public class UInt16UInt16O : Object
{
public UInt16UInt16S UInt16UInt16S { get; private set; }
public UInt16 EmpID { get { return UInt16UInt16S.EmpID; } }
public UInt16 Year { get { return UInt16UInt16S.Year; } }
public List<byte> PayIDs { get; set; }
public override bool Equals(Object obj)
{
if (obj == null || !(obj is UInt16UInt16O)) return false;
UInt16UInt16O item = (UInt16UInt16O)obj;
return (this.EmpID == item.EmpID && this.Year == item.Year);
}
public override int GetHashCode() { return ((UInt32)EmpID << 16 | Year).GetHashCode() ; }
public UInt16UInt16O(UInt16 EmpID, UInt16 Year)
{
UInt16UInt16S uInt16UInt16S = new UInt16UInt16S(EmpID, Year);
this.UInt16UInt16S = uInt16UInt16S;
PayIDs = new List<byte>();
}
public UInt16UInt16O(UInt16 EmpID, UInt16 Year, List<byte> PayIDs)
{
UInt16UInt16S uInt16UInt16S = new UInt16UInt16S(EmpID, Year);
this.UInt16UInt16S = uInt16UInt16S;
this.PayIDs = PayIDs;
}
}
}
}
1000 - 2011 - 1,2,3 1000 - 2012 - 1
。 - Developer