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

การเพิ่มคีย์และค่าที่ระบุลงใน ListDictionary ใน C#

ภาพรวม

ListDictionary.Add(key, value) เพิ่มคู่คีย์/ค่า ใช้ linked list เหมาะข้อมูลน้อย (< 10 รายการ) รองรับ Keys และ IDictionaryEnumerator

ตัวอย่างที่ 1: เพิ่ม 5 คู่และวนลูปด้วย IDictionaryEnumerator

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        ListDictionary dict = new ListDictionary();
        dict.Add("1", "One");
        dict.Add("2", "Two");
        dict.Add("3", "Three");
        dict.Add("4", "Four");
        dict.Add("5", "Five");

        Console.WriteLine("ListDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = dict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

ผลลัพธ์

ListDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five

ตัวอย่างที่ 2: เพิ่ม 10 คู่และแสดงคีย์ทั้งหมด

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        ListDictionary listDict = new ListDictionary();
        listDict.Add("1", 100);
        listDict.Add("2", 200);
        listDict.Add("3", 300);
        listDict.Add("4", 400);
        listDict.Add("5", 500);
        listDict.Add("6", 600);
        listDict.Add("7", 700);
        listDict.Add("8", 800);
        listDict.Add("9", 900);
        listDict.Add("10", 1000);

        ICollection col = listDict.Keys;
        Console.WriteLine("Display all the keys...");
        foreach (String s in col)
        {
            Console.WriteLine(s);
        }
    }
}

ผลลัพธ์

Display all the keys...
1
2
3
4
5
6
7
8
9
10

สรุป

  • ListDictionary ใช้ linked list เหมาะข้อมูลน้อย (ประสิทธิภาพดีกว่า Hashtable เมื่อ < 10 รายการ)
  • คีย์ต้อง unique, ไม่เป็น null
  • รองรับ Keys, Values, GetEnumerator()
  • สำหรับข้อมูลเยอะ ควรใช้ HybridDictionary หรือ Dictionary<TKey,TValue>