使用字典,關鍵需要支持同性運算。例如:
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);
}
}
的字典,只要正確使用,不超過1分的結果 - 這是一個獨特的,關鍵值映射(該值不必是唯一的)。 –