可能重複:
Bidirectional 1 to 1 Dictionary in C#尋找一個數據結構以1對1的唯一依賴
林好奇,如果在標準.NET庫中存在數據結構可以代表1-1關係如下
1-a
4-b
6-c
5-d
我可以說的地方:
thisstructure[1] // returns "a"
thisstructure.GetKey["d"] // return 5
我知道所有的鑰匙必須是唯一的,有類似的東西嗎?
謝謝!
可能重複:
Bidirectional 1 to 1 Dictionary in C#尋找一個數據結構以1對1的唯一依賴
林好奇,如果在標準.NET庫中存在數據結構可以代表1-1關係如下
1-a
4-b
6-c
5-d
我可以說的地方:
thisstructure[1] // returns "a"
thisstructure.GetKey["d"] // return 5
我知道所有的鑰匙必須是唯一的,有類似的東西嗎?
謝謝!
可以將這個方法適合您的需要?
public static class Extensions
{
public static TKey GetKey<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue value)
{
int index = dict.Values.ToList().IndexOf(value);
if (index == -1)
{
return default(TKey); //or maybe throw an exception
}
return dict.Keys.ToList()[index];
}
}
然後,您可以使用它,像這樣:
Dictionary<int, char> dict = new Dictionary<int, char>();
dict.Add(1, 'a');
dict.Add(4, 'b');
dict.Add(6, 'c');
dict.Add(5, 'd');
Console.WriteLine(dict.GetKey('d')); //5
是的,我認爲會。 – greggorob64 2012-07-25 20:29:22
是的 - 它叫做KeyedCollection。它旨在被分類並提供索引訪問以及從添加項目派生的屬性訪問。我通常做一個通用的子類:
public class GenericKeyedCollection<TKey, TValue> : KeyedCollection<TKey, TValue> {
private readonly Func<TValue, TKey> _keyGenerator;
public GenericKeyedCollection(Func<TValue, TKey> keyGenerator) {
_keyGenerator = keyGenerator;
}
protected override int GetKeyForItem(TValue item)
{
return _keyGenerator(item);
}
}
要使用它:
var myCollection = new GenericKeyedCollection<String, Car>(c=>c.Model);
myCollection.Add(new Car("Ford", "Mustang"));
var byIndex = myCollection[0];
var byModel = myCollection["Mustang"];
唯一需要注意的是,該項目已被加入後的衍生屬性(「鑰匙」),不得改變。
如果您的密鑰不是值的屬性,那麼你可以使用一個Tuple<T1, T2>
將鍵和值組合:
var myCollection = new GenericKeyedCollection<String, Tuple<String, Car>>(t=>t.Item1);
myCollection.Add(new Tuple<String, Car>("Foo", Car("Ford", "Mustang")));
var byIndexCar = myCollection[0].Item2;
var byItem1Car = myCollection["Foo"].Item2;
KeyedCollection是.NET 4特有的還是在早期版本中? – Nevyn 2012-07-25 19:46:50
這可以用來解決OP的問題嗎?它看起來不像在OP的情況下可以從值中提取一個密鑰,這似乎是'KeyedCollection
@dasblinkenlight如果OP的值可以是'Tuple
的Dictionary
....或IDictionary
接口是我能想到的最接近到你想要的東西。它沒有那麼簡單的搜索操作,因爲在一個值上搜索可以返回密鑰,但我知道你可以在一個密鑰上搜索來獲得一個值。在自定義擴展類中提供反向功能並不難。
KeyedCollection絕對是更好的選擇。它實現了幕後的字典= D – Nevyn 2012-07-25 19:47:35
在代碼的第二行,你的意思是返回5或信息getKey [ 「一」]?或者我錯過了什麼? – Daniel 2012-07-25 19:37:37
呃,固定。謝謝 – greggorob64 2012-07-25 19:38:20
你是對的dasblinkenlight。我的搜尋fu沒有拿出那個笨蛋。 – greggorob64 2012-07-25 19:40:26