0
点赞
收藏
分享

微信扫一扫

c# 利用ContainsKey方法判断Dictionary中是否包含某个键

覃榜言 2023-12-16 阅读 62

ContainsKey的定义

命名空间:
System.Collections.Generic
程序集:
System.Collections.dll

原型

public bool ContainsKey (TKey key);
确定是否 Dictionary<TKey,TValue> 包含指定键。

参数

key TKey
要在 Dictionary<TKey,TValue> 中定位的键。

返回

Boolean
如果 true 包含具有指定键的元素,则为 Dictionary<TKey,TValue>;否则为 false。

示例代码

代码

using System;
using System.Collections.Generic;

namespace Niaoge
{
    class Program
    {
        static void Main(string[] args)
        {
            // 新建字典
            var d = new Dictionary<string, string>();

            // 向字典中添加内容
            d.Add("key1", "value1");
            d.Add("key2", "value2");
            d.Add("key3", "value3");

            if (d.ContainsKey("key1"))
            {
                Console.WriteLine("key1已经存在");
            }
            else
            {
                Console.WriteLine("key1不存在");
            }
			

            if (d.ContainsKey("haha"))
            {
                Console.WriteLine("haha已经存在");
            }
            else
            {
                Console.WriteLine("haha不存在");
            }

            Console.ReadKey();
        }
    }
}

运行结果

参考

[文档] https://learn.microsoft.com/zh-cn/dotnet/csharp/
[源码] https://referencesource.microsoft.com/
[平台] https://www.csdn.net
[论坛] https://stackoverflow.co/

总结

利用函数ContainsKey,可以查询Dictionary 中某个键是否已经存在。
如果函数返回true,表明字典中已经存在某个键;
如果函数返回false,表明字典中不存在某个键。


举报

相关推荐

0 条评论