在C#中查询字典的最佳方法

8

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

8个回答

21

如果您知道字典中包含该键:

value = dictionary[key];

如果你不确定:

dictionary.TryGetValue(key, out value);

如果您想要检查该值,可以快速执行以下操作:if(!dic.TryGetValue(key, out object o) || o == null) return; - Fabrice T

10

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

这是访问字典键值对的标准方式:

var theValue = myDict[key];
如果键不存在,这将抛出一个异常,因此在获取它之前,您可能需要先检查键是否存在(不是线程安全的):
if(myDict.ContainsKey(key))
{
   var theValue = myDict[key];
}

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


4
myDict.TryGetValue更高效,因为它只需要计算一次键,而不像Contains后跟一个索引器要计算两次。 - Martin
@Martin:我敢打赌关键字查找的操作是O(1),所以不用担心。无论如何,+1。 - zerkms
@Martin,不过它确实需要一个需要预先声明的“out”参数。 - Oded
@zerkms,键值查找可能是O(1),但这仍然会累加。此外,GetHashCode可能是O(任何内容),因为它是在键的类中实现的。 - Martin
3
@Oded 个人而言,我会在字典上创建一个扩展方法 GetValueOrDefault(key),它在内部使用 TryGetValue 并返回默认值(如果没有这样的项)。 - Martin
@Martin - 听起来像是一个不错的扩展方法。 - Oded

6
如果您想对字典集合进行查询,可以按照以下方式操作:
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
var stringValue = dictionary[key];

3
string value = dictionary[key];

3
你能不能像这样做些什么呢:var value = myDictionary[i];

2

我不太确定你在问什么,但我猜想这与字典有关?

如果你知道键值,获取字符串值是相当容易的。

string myValue = myDictionary[yourKey];

如果您想像索引器一样使用它(如果这个字典是在一个类中),您可以使用以下代码。
public class MyClass
{
  private Dictionary<string, string> myDictionary;

  public string this[string key]
  {
    get { return myDictionary[key]; }
  }
}

2

Dictionary.TryGetValue 是最安全的方法,或者像其他人建议的那样使用 Dictionary 索引器,但记得要捕获 KeyNotFoundException 异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接