如何在字典集合中查找项目?

时间:2011-04-03 16:59:59

标签: c# generics dictionary

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

protected static Dictionary<string, string> _tags;

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

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

我收到错误:

  

运算符'!''不能应用于'System.Collections.Generic.KeyValuePair'和''

类型的操作数

最初我尝试将结果与null进行比较,我想struct s不支持。

我会认为在一个集合中找到一个项目是一项非常简单的任务。那么我如何确定是否找到了我正在寻找的物品?

(注意:我正在使用Dictionary,因为我想要快速查找。我知道我可以使用Contains()来确定项目是否在那里。但这意味着总共有两个查找,排序失败了快速查找的目的。我很乐意使用不同的集合,如果它可以快速查找项目,我有办法确定它是否成功。)

4 个答案:

答案 0 :(得分:89)

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

是一种低效且有点奇怪的方法,可以通过字典中的键来查找内容。查找密钥是字典的基本功能。

基本解决方案是:

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

答案 1 :(得分:7)

如果您必须进行不同的测试,有时您仍需要使用FirstOrDefault。 如果您的词典的Key组件可以为空,那么您可以这样做:

thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }

使用FirstOrDefault,如果找不到匹配项,返回的KeyValuePair的键和值都将为null。

答案 2 :(得分:0)

当然,如果你想确定它在那里,否则失败,那么这是有效的:

thisTag = _tags [key];

注意:如果键值对不存在但有时这正是您想要的,则会失败。 这样你就可以捕获它并对错误做些什么。 我只会这样做,如果我确定键,值对是或应该在字典中,如果不是,我希望它通过throw来了解它。

答案 3 :(得分:0)

可以使用ContainsKey或TryGetValue在Dictionary集合中找到元素,如下所示:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    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);
        }
    }
}
相关问题