要使用字典,键需要支持相等操作。例如:
public class ICD_Map2 : IEquatable<ICD_Map2>
{
public ICD_Map2(string callType, string destination) {
CallType = callType;
Destination = destination;
}
public override int GetHashCode() {
int result = 17;
result = -13 * result +
(CallType == null ? 0 : CallType.GetHashCode());
result = -13 * result +
(Destination == null ? 0 : Destination.GetHashCode());
return result;
}
public override bool Equals(object other) {
return Equals(other as ICD_Map2);
}
public bool Equals(ICD_Map2 other) {
if(other == null) return false;
if(other == this) return true;
return CallType == other.CallType && Destination == other.Destination;
}
public string CallType {get; private set; }
public string Destination{get; private set;}
}
注意将其设为只读是有意的:可变键会导致巨大的问题 - 避免这种情况。
现在您可以将其用作键,例如:
var key = new ICD_Map2("Mobile SMS", "Australia");
string result;
if(maps.TryGetValue(key, out result)) {
Console.WriteLine("found: " + result);
}
反向查找是有问题的,除非您有第二个字典,否则无法优化。一个简单的操作(性能 O(n))将是:
string result = "International Text";
var key = (from pair in maps
where pair.Value == result
select pair.Key).FirstOrDefault();
if(key != null) {
Console.WriteLine("found: " + key);
}
把它们放在一起:
static void Main()
{
Dictionary<ICD_Map2, string> maps = new Dictionary<ICD_Map2, string> {
{new ICD_Map2 ("Mobile SMS", "Australia"),"Local Text"},
{new ICD_Map2 ("Mobile SMS", "International"),"International Text"}
};
// try forwards lookup
var key = new ICD_Map2("Mobile SMS", "Australia");
string result;
if (maps.TryGetValue(key, out result))
{
Console.WriteLine("found: " + result);
}
// try reverse lookup (less efficient)
result = "International Text";
key = (from pair in maps
where pair.Value == result
select pair.Key).FirstOrDefault();
if (key != null)
{
Console.WriteLine("found: " + key);
}
}