首页 > 编程语言 >c# Dictionary.TryGetValue()的用法

c# Dictionary.TryGetValue()的用法

时间:2022-08-24 12:14:21浏览次数:79  
标签:TryGetValue Dictionary c# value int key ContainsKey out

官方解释

 上面解释:1)TryGetValue是根据key返回相应的数据到value,如果没有key则返回默认值到value;

      2)这个方法的返回是bool值,如果dictionary里有存在相应的key为true,没有存在,则为false

例子1

using System;
using System.Collections.Generic;

namespace TryGetValueExp
{
    class Program
    {
        static void Main(string[] args)
        {
            var counts = new Dictionary<string, int>();
            counts.Add("key", 0);
            int value;//这个变量用来存储TryGetValue返回的相应key的value.
            if (counts.TryGetValue("key", out value))
            {
                counts["key"] = value + 1;
                Console.WriteLine("Value: " + counts["key"]);
            }
        }
    }
}

测试结果如下:

例子2

除上面例子1的写法外,也可以通过参数指定“out”类型

//例子二:
            var ids = new Dictionary<string, bool>() { { "A", true } };
            //我们可以通过参数指定“out”类型,如下:
            if (ids.TryGetValue("A",out bool result))
            {
                Console.WriteLine($"Value:{result}");
            }

测试结果如下:

 ContainsKey与TryGetValue对比

1)当确定字典中存在该键值对时,可以使用ContainsKey:

 

2) 当在字典中不能确定是否存在该键时需要使用TryGetValue,以减少一次不必要的查找,同时避免了判断Key值是否存在而引发的“给定关键字不在字典中。”的错误。

3)两者性能对比:

  //例子三:
            const int _max = 10000000;
            var test = new Dictionary<string, int>();
            test["key"] = 1;
            int sum = 0;
            //法一:用ContainsKey获取对应key的value值
            var s1 = Stopwatch.StartNew();
            for (int i = 0; i < _max; i++)
            {
                if (test.ContainsKey("key"))
                {
                    sum += test["key"];
                }
            }
            s1.Stop();
            //法二:用TryGetValue获取对应key的value值
            var s2 = Stopwatch.StartNew();
            for (int i = 0; i < _max; i++)
            {
                if (test.TryGetValue("key", out int r))
                {
                    sum += r;
                }
            }
            s2.Stop();
            Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
            Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));

测试结果如下:

 从上面测试结果看:

TryGetValue取值比用ContainsKey更快。原因是:使用ContainsKey,如果键存在,则会在每次循环中再次取值,但TryGetValue,会直接存储结果值,然后马上用于求和。

 

 参考网址:

https://www.dotnetperls.com/trygetvalue

https://blog.csdn.net/qq_38721111/article/details/83508909

https://blog.csdn.net/joyhen/article/details/9310743

代码存于:..CSharpBasic\TryGetValueExp

标签:TryGetValue,Dictionary,c#,value,int,key,ContainsKey,out
From: https://www.cnblogs.com/keeplearningandsharing/p/16619160.html

相关文章