C# 中的字典方法
字典是 C# 中的一組鍵和值。Dictionary<TKey, TValue> 包含在 System.Collection.Generics 名稱空間中。
以下為方法 −
| 序數 | 方法及說明 |
|---|---|
| 1 | Add 在字典中新增鍵值對 |
| 2 | Clear() 移除所有鍵和值 |
| 3 | Remove 移除指定鍵的元素。 |
| 4 | ContainsKey 檢查指定的鍵是否存在於 Dictionary<TKey, TValue> 中。 |
| 5 | ContainsValue 檢查指定的鍵值是否存在於 Dictionary<TKey, TValue> 中。 |
| 6 | Count 計算鍵值對的數量。 |
| 7 | Clear 從 Dictionary<TKey, TValue> 中移除所有元素。 |
讓我們瞭解如何在字典中新增元素並顯示數量。
例項
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);
d.Add(5,78);
d.Add(6,98);
Console.WriteLine(d.Count);
}
}輸出
6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP