[英]Create a Dictionary with multiple keys and get value using one of keys
我想創建一個具有多個鍵的Dictionary
,並且當我想僅使用一個或多個鍵來獲取值時。
我試過 :
Dictionary<Tuple<int, string>, string> dictionary = new Dictionary<Tuple<int, string>, string>();
var Key =new Tuple<int,string>(1,"I1");
var Value = "this is a value";
dictionary.Add(Key, Value);
當我嘗試從dictionary
獲取值時,我必須/應該輸入所有鍵
像這樣 :
MessageBox.Show($"{dictionary[new Tuple<int, string>(1,"I1")]}");
但是當我嘗試僅使用這樣的鍵之一來獲取價值時
MessageBox.Show($"{dictionary[new Tuple<int, string>(1,"")]}");
我收到錯誤,我知道發生此錯誤是因為dictionary
需要完整的存在鍵才能返回值。
因此,請任何人都知道如何創建具有多個keys
的Dictionary
以及僅使用一個或多個或所有keys
檢索值時的任何想法?
.NET 中的字典預計具有接近 O(1) 的查找時間。 為了實現這一點,他們使用了關鍵對象的GetHashCode()
和Equals()
方法。 生成的哈希碼用於將字典的內容划分為多個分區。 當您查找一個項目時,分區是使用哈希代碼標識的,該分區中具有匹配哈希代碼* 的所有項目將與您使用Equals()
方法查找的鍵進行比較。
在這里,您嘗試為每個對象創建一個帶有兩個鍵的字典。 您正在使用Tuple
來制作一個鍵。 Tuple
的GetHashCode()
結果基於它的兩個值,因此如果您只想按鍵的一半查找值,就會失去字典的性能。 您需要瀏覽整個字典,比較每個單獨的項目,使其比列表好一點。
一種解決方案是制作一個具有 string->int 鍵查找的字典,然后另一個字典就是 int->string。 這在使用字符串鍵時需要兩次查找,但可能是一個很好的解決方案。
例子:
Dictionary<string, int> stringKeyToIntKey = new Dictionary<string, int>();
Dictionary<int, string> intKeyDict = new Dictionary<int, string>();
intKeyDict[1] = "Test";
stringKeyToIntKey["I1"] = 1;
Console.WriteLine(intKeyDict[1]);
Console.WriteLine(intKeyDict[stringKeyToIntKey["I1"]]);
添加方法可能如下所示:
public void AddEntry(int intKey, string stringKey, string value)
{
intKeyDict[intKey] = value;
stringKeyToIntKey[stringKey] = intKey;
}
您可以包裝 TryGetValue 以使生活更輕松:
public bool TryGetValue(string stringKey, out string value)
{
value = null;
return stringKeyToIntKey.TryGetValue(stringKey, out int intKey) && intKeyDict.TryGetValue(intKey, out value);
}
刪除看起來像這樣:
public void DeleteEntry(string stringKey)
{
if (stringKeyToIntKey.TryGetValue(stringKey, out int intKey))
{
intKeyDict.Remove(intKey);
stringKeyToIntKey.Remove(stringKey);
}
}
您必須確保同時從兩個詞典中添加和刪除項目。 當您向intKey
添加項目時,您需要將相應的鍵映射添加到stringKeyToIntKey
。
或者,您可以有兩個字典:一個帶有字符串鍵,一個帶有 int 鍵,並且每個都具有相同的值。 同樣,您必須同時添加和刪除項目,並且還必須同時更新兩者中的值。
例子:
Dictionary<string, string> stringKeyDict = new Dictionary<string, string>();
Dictionary<int, string> intKeyDict = new Dictionary<int, string>();
stringKeyDict["I1"] = "hello";
intKeyDict[1] = "hello";
Console.WriteLine(stringKeyDict["I1"]);
Console.WriteLine(intKeyDict[1]);
這是我最喜歡的方法,其中值是類實例,因為兩個字典將為我的項目引用相同的類實例,因此對這些實例的屬性的更改將反映在兩者中。 但是,對於字符串,第一個選項可能更好。
*哈希碼不是唯一的,多個對象可能具有相同的哈希碼,即使它們的值不同
您可以使用字符串作為字典鍵。 假設您想從int x = 5
和string y = "str".
創建一個鍵string y = "str".
您可以使用一些分隔符連接和拆分它們,並創建一個像這樣的鍵:
string key = $"{x}:{y}"
假設您只想通過 x 獲取元素。 你可以這樣寫:
dictionary.Where(kvp=>kvp.Key.Contains($"{x}:"))
當然,它不會在 O(1) 時間內給出元素(它會在 O(n) 時間內給出元素)但它會起作用。 如果您只想通過 x 在 O(1) 時間內獲取元素,我不確定是否可以使用一本字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.