2010-11-14 33 views

回答

16

如果你知道,關鍵是在詞典:

value = dictionary[key]; 

如果你不知道:

dictionary.TryGetValue(key, out value); 
+0

@ Joe ..感謝您的幫助 – Ananth 2010-11-14 13:23:55

2

你能不能做這樣的事情:

var value = myDictionary[i];

+0

@Serg。 。感謝您的幫助 – Ananth 2010-11-14 13:25:01

3
var stringValue = dictionary[key]; 
+0

@ Zerkms Thanks .... – Ananth 2010-11-14 13:17:21

8

你是什麼意思最好?

這是通過密鑰來訪問Dictionary標準方式:

var theValue = myDict[key]; 

如果該鍵不存在,這將拋出一個異常,那麼您可能想看看他們是否關鍵梯之前存在它(不是線程安全):

if(myDict.ContainsKey(key)) 
{ 
    var theValue = myDict[key]; 
} 

或者,你可以使用myDict.TryGetValue,儘管這需要使用out參數,以獲得的價值。

+0

讓我們彼此高興 - 至少會公平))) – zerkms 2010-11-14 13:14:21

+4

myDict.TryGetValue更高效,因爲它只需計算一次密鑰,不像Contains後面跟着一個indexre,它會執行兩次。 – Martin 2010-11-14 13:15:27

+0

@Martin:我敢打賭,鍵查找的操作是'O(1)',所以不必擔心。無論如何,+1 – zerkms 2010-11-14 13:16:38

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;