代码之家  ›  专栏  ›  技术社区  ›  Ananth

用C语言查询词典的最佳方法#

  •  6
  • Ananth  · 技术社区  · 15 年前

    例如,我有一本字典 Dictionary<int, string> .
    如果我知道这个键,那么获取字符串值的最佳方法是什么?

    8 回复  |  直到 15 年前
        1
  •  18
  •   to StackOverflow    15 年前

    如果您知道密钥在字典中:

    value = dictionary[key];
    

    如果您不确定:

    dictionary.TryGetValue(key, out value);
    
        2
  •  10
  •   Oded    15 年前

    你说“最好”是什么意思?

    这就是 标准 进入途径 Dictionary 关键值:

    var theValue = myDict[key];
    

    如果键不存在,这将引发异常,因此您可能希望在获取键之前查看它们是否存在(不是线程安全的):

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

    或者,你可以使用 myDict.TryGetValue 但这需要使用out参数才能获取值。

        3
  •  5
  •   Scott    15 年前

    如果要查询字典集合,可以执行以下操作:

    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;
    
        4
  •  4
  •   zerkms    15 年前
    var stringValue = dictionary[key];
    
        5
  •  3
  •   delete    15 年前

    你不能这样做吗?

    var value = myDictionary[i]; ?

        6
  •  3
  •   Diego Mijelshon    15 年前
    string value = dictionary[key];
    
        7
  •  2
  •   Captain Comic    15 年前

    Dictionary.TryGetValue 是最安全的方法 或者按照其他建议使用字典索引器,但请记住捕获keynotfoundexception

        8
  •  2
  •   Michiel Peeters    15 年前

    好吧,我不太确定你在这里问什么,但我想是关于一本字典?

    如果知道键,就很容易得到字符串值。

    string myValue = myDictionary[yourKey];
    

    如果要像索引器那样使用(如果此字典在类中),可以使用以下代码。

    public class MyClass
    {
      private Dictionary<string, string> myDictionary;
    
      public string this[string key]
      {
        get { return myDictionary[key]; }
      }
    }
    
    推荐文章