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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP