我有一本字典,例如Dictionary<int, string>
。
如果我知道密鑰,那麼獲取字符串值的最佳方法是什麼?在C中查詢字典的最佳方法#
5
A
回答
16
如果你知道,關鍵是在詞典:
value = dictionary[key];
如果你不知道:
dictionary.TryGetValue(key, out value);
2
3
8
你是什麼意思最好?
這是通過密鑰來訪問Dictionary
值標準方式:
var theValue = myDict[key];
如果該鍵不存在,這將拋出一個異常,那麼您可能想看看他們是否關鍵梯之前存在它(不是線程安全):
if(myDict.ContainsKey(key))
{
var theValue = myDict[key];
}
或者,你可以使用myDict.TryGetValue
,儘管這需要使用out參數,以獲得的價值。
2
string value = dictionary[key];
1
Dictionary.TryGetValue
是最安全的方法 或使用字典索引其他建議,但記得要趕KeyNotFoundException
+0
@漫畫..感謝您的幫助 – Ananth 2010-11-14 13:31:55
1
好吧我不是確定你在這裏問什麼,但我想這是關於一個詞典?
如果您知道密鑰,那麼獲取字符串值是相當容易的。
string myValue = myDictionary[yourKey];
如果您想使用像索引器(如果此字典在類中),您可以使用下面的代碼。
public class MyClass
{
private Dictionary<string, string> myDictionary;
public string this[string key]
{
get { return myDictionary[key]; }
}
}
4
如果您想查詢對一個字典集合,你可以做到以下幾點:
static class TestDictionary
{
static void Main() {
Dictionary<int, string> numbers;
numbers = new Dictionary<int, string>();
numbers.Add(0, "zero");
numbers.Add(1, "one");
numbers.Add(2, "two");
numbers.Add(3, "three");
numbers.Add(4, "four");
var query =
from n in numbers
where (n.Value.StartsWith("t"))
select n.Value;
}
}
您還可以使用n.Key屬性,像這樣
var evenNumbers =
from n in numbers
where (n.Key % 2) == 0
select n.Value;
相關問題
- 1. 在sql中查詢數據字典的最佳方法
- 2. 在c#中建立動態linq查詢的最佳方法?
- 3. 檢查列表字典中是否有值的最佳方法?
- 4. C#在字典中搜索字典的最快方法
- 5. 最佳方式字典
- 6. 查詢可靠的字典集合的最佳方法是什麼
- 7. 解析C#中字符串查詢字符串的最佳方法
- 8. C#從數據庫查詢中降級的最佳方法
- 9. 查詢DynamoDB的最佳方法
- 10. 查詢TypedDataSet的最佳方法
- 11. 構建查詢的最佳方法?
- 12. 測試HTTP查詢的最佳方法
- 13. 在文件中存儲大型Python字典的最佳方法
- 14. 在Python中過濾字典的最佳方法
- 15. 在MySql查詢中檢查NULL值的最佳方法
- 16. 檢查大小寫查詢字符串的最佳方法
- 17. 檢查查詢字符串是否爲int的最佳方法?
- 18. Swift - 處理字典詞典的最佳方法?
- 19. 查詢邏輯最佳方法
- 20. 動態查詢數據 - 最佳方法
- 21. 在C#中查詢XML的最佳方式 - 使用LINQ等
- 22. 什麼是封裝ADO.Net查詢的最佳c#方法
- 23. SQL/C# - 執行查詢的最佳方法
- 24. Django查詢查詢集的模型類型的最佳方法
- 25. 最佳方式查詢
- 26. 刪除字典列表中重複值的最佳方法?
- 27. Python:跟蹤字典中特定值的最佳方法
- 28. 從字典中獲取單個密鑰的最佳方法?
- 29. 從Python字典中刪除項目的最佳方法?
- 30. Mysql查詢。獲取查詢的最佳方法
@ Joe ..感謝您的幫助 – Ananth 2010-11-14 13:23:55