C# ContainsKey(Object):确定集合是否包含具有指定键的元素

  • Post category:C#

C# ContainsKey(Object) 方法攻略

简介

ContainsKey(Object) 方法属于C#中的Dictionary类,该方法用于判断字典中是否包含指定的键。如果包含该键,则返回true,否则返回false。

语法

public bool ContainsKey(object key);

参数

  • key:要在字典中查找的键。

返回值

如果字典包含指定的键,则返回true,否则返回false。

示例

示例1:使用ContainsKey()方法判断字典中是否包含指定的键

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "苹果");
dict.Add(2, "橙子");
dict.Add(3, "葡萄");
dict.Add(4, "香蕉");

bool containsKey = dict.ContainsKey(3);

if (containsKey)
{
    Console.WriteLine("字典中包含键3");
}
else
{
    Console.WriteLine("字典中不包含键3");
}

输出结果:

字典中包含键3

示例2:在控制台应用程序中使用ContainsKey()方法判断字典中是否包含指定的键

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();

            dict.Add("Tom", 25);
            dict.Add("Jerry", 28);
            dict.Add("Mike", 30);

            Console.Write("请输入要查找的姓名:");
            string name = Console.ReadLine();

            bool containsKey = dict.ContainsKey(name);

            if (containsKey)
            {
                int age = dict[name];
                Console.WriteLine("{0}的年龄是{1}岁", name, age);
            }
            else
            {
                Console.WriteLine("字典中不包含姓名为{0}的记录", name);
            }

            Console.ReadLine();
        }
    }
}

输出结果:

请输入要查找的姓名:Mike
Mike的年龄是30岁

总结

ContainsKey()方法是Dictionary类中的一个重要方法,用于判断字典中是否包含指定的键。本文介绍了该方法的语法、参数、返回值,并给出了两个示例说明,希望能够帮助大家更好的理解该方法的使用。