如何在字典集合中查找项目? [英] How to Find Item in Dictionary Collection?

查看:80
本文介绍了如何在字典集合中查找项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have declared and populated the following collection.

protected static Dictionary<string, string> _tags;

现在我想看看在集合中找到一个特定的条目。我尝试了以下内容。

Now I want to look locate a particular entry in the collection. I tried the following.

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

我收到错误:


运算符'!='不能应用于类型为System.Collections的操作数。 Generic.KeyValuePair'和''

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

最初我试图将结果与 null ,我想这不支持 struct s。

Initially I attempted to compare the result to null, and I guess that's not supported with structs.

我以为找到一个项目在一个集合中是一个非常微不足道的任务。那么如何找到我正在寻找的项目?

I would've thought that finding an item within a collection is a very trivial task. So how the heck to I determine if the item I'm looking for was found?

(注意:我使用字典因为我想要快速查找,我知道我可以使用 Contains()确定项目是否存在,但这意味着总共有两个查找,失败了快速查找的目的,如果快速查找项目,我可以快乐地使用一个不同的集合,并且我有一个方法可以确定它是否成功。)

(Note: I'm using Dictionary because I want fast lookups. I know I can use Contains() to determine if the item is there. But that means a total of two lookups, which sort of defeats the purpose of having a fast lookup. I'll happily using a different collection if it can quickly lookup an item and I have a way to determine if it was successful.)

推荐答案

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

是一种无效的,有点奇怪的方式,通过字典中的键来找到东西。寻找钥匙是一个字典的基本功能。

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

基本解决方案是:

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

但这需要2次查找。

TryGetValue(key,out value)更简洁有效,只能进行1次查找。这回答了您问题的最后一部分:

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question:

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






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


VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

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

这篇关于如何在字典集合中查找项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆