c# - 如何在词典集中查找项目?

标签 c# generics dictionary

我已经声明并填充了以下集合。

protected static Dictionary<string, string> _tags;

现在我想查找集合中的特定条目。我尝试了以下方法。

thisTag = _tags.FirstOrDefault(t => t.Key == tag);
if (thisTag != default(KeyValuePair<string, string>))
    ...

我得到了错误:

Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair' and ''

最初我试图将结果与 null 进行比较,但我猜 struct 不支持这种做法。

我原以为在集合中查找项目是一项非常微不足道的任务。那么我究竟该如何确定是否找到了我正在寻找的项目呢?

(注意:我正在使用 Dictionary 因为我想要快速查找。我知道我可以使用 Contains() 来确定该项目是否存在。但这意味着总共两次查找,这有点违背了快速查找的目的。如果它可以快速查找一个项目并且我有办法确定它是否成功,我会很乐意使用不同的集合。)

最佳答案

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

是一种在字典中按键查找内容的低效且有点奇怪的方法。查找 Key 是 Dictionary 的基本功能。

基本的解决方案是:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

但这需要 2 次查找。

TryGetValue(key, out value) 更简洁高效,它只做 1 次查找。这回答了你问题的最后一部分,进行查找的最佳方法是:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 更新,对于 C# 7 及更高版本,我们可以内联声明结果变量:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

关于c# - 如何在词典集中查找项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5531042/

相关文章:

generics - 为什么通用代数数据类型需要 `T` 成员类型?

generics - 为什么 Send on trait implementations 的 trait bounds 被忽略?

python - 为列表或字典中的每个项目添加年份

c# - GroupBox 在 WPF 的深色背景上显示不正确

c# - 打印大型 WPF 用户控件

c# - C# 中的静态泛型方法

python - 无序列表作为字典键

c# - Entity Framework - 不支持列 'ColumnName' 的类型。类型是 'Object'

c# - c#中的>>运算符是什么

Python:多维字典到数组