C# 程序查找字典中的键


首先,设置包含元素的 Dictionary 集合。

Dictionary<int, string> d = new Dictionary<int, string>() {
   {1,"Applianes"},
   {2, "Clothing"},
   {3,"Toys"},
   {4,"Footwear"},
   {5, "Accessories"}
};

现在,假设你需要检查键 5 是否存在。为此,可以使用 ContainsKey() 方法。如果找到键,该方法将返回 True。

d.ContainsKey(5);

我们来看看完整的代码。

示例

 在线演示

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>() {
         {1,"Electronics"},
         {2, "Clothing"},
         {3,"Toys"},
         {4,"Footwear"},
         {5, "Accessories"}
      };
      foreach (KeyValuePair<int, string> ele in d) {
         Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
      }
      Console.WriteLine("Key 5 exists? "+d.ContainsKey(5));
   }
}

输出

Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
Key 5 exists? True

更新于:2020 年 6 月 23 日

233 次浏览

提升您的 职业

完成课程即可获得认证

开始吧
广告