如何在字典集合中查找项目?
我已经声明并填充了以下集合。
protected static Dictionary _tags;
现在我想查找集合中的特定条目。 我尝试了以下内容。
thisTag = _tags.FirstOrDefault(t => t.Key == tag); if (thisTag != default(KeyValuePair)) ...
我收到错误:
运算符’!=’不能应用于’System.Collections.Generic.KeyValuePair’和”类型的操作数
最初我试图将结果与null
进行比较,我猜struct
不支持。
我会认为在一个集合中找到一个项目是一项非常简单的任务。 那么我如何确定是否找到了我正在寻找的物品?
(注意:我正在使用Dictionary
因为我想要快速查找。我知道我可以使用Contains()
来确定项目是否存在。但这意味着总共有两次查找,这有点挫败了快速查找的目的如果可以快速查找项目,我会愉快地使用不同的集合,我有办法确定它是否成功。)
thisTag = _tags.FirstOrDefault(t => t.Key == tag);
在字典中按键找到某些东西是一种低效且有点奇怪的方法。 为Key找东西是Dictionary的基本function。
基本解决方案是:
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
如果您必须进行不同的测试,有时您仍然需要使用FirstOrDefault。 如果您的词典的Key组件可以为空,则可以执行以下操作:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a'); if(thisTag.Key != null) { ... }
使用FirstOrDefault,如果找不到匹配项,则返回的KeyValuePair的键和值都将为null。
当然,如果你想确保它在那里,否则失败然后这工作:
thisTag = _tags [key];
注意:如果键值对不存在但有时这正是您想要的,则会失败。 通过这种方式,您可以捕获它并对错误执行某些操作。 我只会这样做,如果我确定键,值对是或应该在字典中,如果不是我希望它通过throw知道它。
可以使用ContainsKey或TryGetValue在Dictionary集合中找到元素,如下所示:
class Program { protected static Dictionary _tags = new Dictionary(); static void Main(string[] args) { string strValue; _tags.Add("101", "C#"); _tags.Add("102", "ASP.NET"); if (_tags.ContainsKey("101")) { strValue = _tags["101"]; Console.WriteLine(strValue); } if (_tags.TryGetValue("101", out strValue)) { Console.WriteLine(strValue); } } }