在 C# 中,可以使用'ContainsKey'方法来判断字典中是否存在指定的键。以下是一个示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>();
        dict.Add('key1', 1);
        dict.Add('key2', 2);
        dict.Add('key3', 3);

        string keyToFind = 'key2';

        if (dict.ContainsKey(keyToFind))
        {
            Console.WriteLine('字典中存在键 {0}', keyToFind);
        }
        else
        {
            Console.WriteLine('字典中不存在键 {0}', keyToFind);
        }
    }
}

运行以上代码,输出结果为:

字典中存在键 key2
C# 遍历字典查找指定键:ContainsKey 方法详解

原文地址: https://www.cveoy.top/t/topic/bsQ6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录