如何找到项词典集? [英] How to Find Item in Dictionary Collection?
问题描述
我已经宣布并填充以下集合
受保护的静态字典<字符串,字符串> _tags;
现在我想看看找到集合在一个特定的条目。我尝试了以下
thisTag = _tags.FirstOrDefault(T => t.Key ==标签);
如果(thisTag =默认(KeyValuePair<!字符串,字符串>))
...
和我得到的错误:
运算符'!='不能应用于类型'的System.Collections中的操作数。 Generic.KeyValuePair'和''
块引用>
起初我试图比较结果
空
,我想,这不是与结构
所支持的。
我会一直以为找到一个项目集合中是一个非常简单的任务。 ?那么如何赫克我确定,如果我要找的项目被发现。
(注:我使用
词典
,因为我想快速查找。我知道我可以使用包含()
来确定,如果该项目是存在的。但是,这意味着一共有两个查找,其中排序的失败具有快速查询的目的。我会愉快地使用不同的集合,如果它能迅速查找一个项目,我有一个办法,以确定它是否是成功的。)
解决方案thisTag = _tags.FirstOrDefault(T => t.Key ==标签);
是一个低效率,并找到钥匙在字典中的东西一点点奇怪的方式。 。找东西的关键是一本字典的基本功能
基本的解决办法是:
如果(_tags.Containskey(标签)){字符串myvalue的= _tags [标签] ...}
但是,这需要2查找。
TryGetValue(键,超时值)
更加简洁高效,它只做1查找。这回答你的问题的最后一部分:字符串myvalue的;
如果(_tags.TryGetValue(标签,出myvalue的)){/ *使用myvalue的* /}
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>)) ...
And I get the error:
Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair' and ''
Initially I attempted to compare the result to
null
, and I guess that's not supported withstruct
s.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?
(Note: I'm using
Dictionary
because I want fast lookups. I know I can useContains()
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.
The basic solution would be:
if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
But that requires 2 lookups.
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 */ }
这篇关于如何找到项词典集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!