Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การทำงานกับ Hashtable และ Dictionary ใน C#

Hashtable

คลาส Hashtable แสดงถึงคอลเลกชันของคู่คีย์-ค่า (key-value pairs) ที่จัดระเบียบตามรหัสแฮชของคีย์ ใช้คีย์ในการเข้าถึงสมาชิกในคอลเลกชัน

เมธอดที่ใช้บ่อยใน Hashtable:

No.Method & Description
1Add(object key, object value)
เพิ่มสมาชิกพร้อมคีย์และค่าที่ระบุ
2Clear()
ลบสมาชิกทั้งหมดออกจาก Hashtable
3ContainsKey(object key)
ตรวจสอบว่า Hashtable มีคีย์เฉพาะเจาะจงหรือไม่
4ContainsValue(object value)
ตรวจสอบว่า Hashtable มีค่าเฉพาะเจาะจงหรือไม่

ตัวอย่าง Hashtable

using System;
using System.Collections;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            Hashtable ht = new Hashtable();
            ht.Add("D01", "Finance");
            ht.Add("D02", "HR");
            ht.Add("D03", "Operations");
            
            if (ht.ContainsValue("Marketing")) {
                Console.WriteLine("This department name is already in the list");
            } else {
                ht.Add("D04", "Marketing");
            }
            
            ICollection key = ht.Keys;
            foreach (string k in key) {
                Console.WriteLine(k + ": " + ht[k]);
            }
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

D04: Marketing
D02: HR
D03: Operations
D01: Finance

Dictionary

Dictionary<TKey, TValue> เป็นคอลเลกชันของคีย์และค่าใน C# อยู่ในเนมสเปซ System.Collections.Generic

เมธอดหลัก:

No.Methods & Description
1Add - เพิ่มคู่คีย์-ค่า
2Clear() - ลบคีย์และค่าทั้งหมด
3Remove - ลบสมาชิกด้วยคีย์ที่ระบุ
4ContainsKey - ตรวจสอบคีย์ที่มีอยู่
5ContainsValue - ตรวจสอบค่าที่มีอยู่
6Count - นับจำนวนคู่คีย์-ค่า

ตัวอย่าง Dictionary

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        IDictionary<int, int> d = new Dictionary<int, int>();
        d.Add(1, 44);
        d.Add(2, 34);
        d.Add(3, 66);
        d.Add(4, 47);
        d.Add(5, 76);
        Console.WriteLine(d.Count);
    }
}

ผลลัพธ์

5