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

问题描述 投票:0回答:4

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

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()
来确定该项目是否存在。但这意味着总共两次查找,这有点违背了快速查找。如果可以快速查找项目并且我有办法确定它是否成功,我会很高兴使用不同的集合。)

c# generics dictionary
4个回答
134
投票
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

8
投票

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

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

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


3
投票

可以使用 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);
        }
    }
}

0
投票

当然,如果你想确保它在那里,否则会失败,那么这是可行的:

这个标签 = _tags[key];

注意:如果键值对不存在,这将失败,但有时这正是您想要的。 这样您就可以捕获它并对错误采取一些措施。 只有当我确定键值对在或应该在字典中时,我才会这样做,如果不是,我希望它通过抛出来了解它。

© www.soinside.com 2019 - 2024. All rights reserved.