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

การรับตัวแปรนับที่วนซ้ำผ่าน StringDictionary ใน C#

ภาพรวม

StringDictionary (ใน System.Collections.Specialized) เก็บคู่คีย์/ค่าแบบสตริง สามารถวนซ้ำได้ด้วย foreach หรือ IEnumerator จาก GetEnumerator()

ตัวอย่าง 1: ใช้ foreach และ IEnumerator

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

public class Demo {
    public static void Main() {
        StringDictionary strDict1 = new StringDictionary();
        strDict1.Add("A", "John");
        strDict1.Add("B", "Andy");
        strDict1.Add("C", "Tim");
        strDict1.Add("D", "Ryan");
        strDict1.Add("E", "Kevin");
        strDict1.Add("F", "Katie");
        strDict1.Add("G", "Brad");

        Console.WriteLine("StringDictionary1 elements...");
        foreach (DictionaryEntry de in strDict1) {
            Console.WriteLine(de.Key + " " + de.Value);
        }

        StringDictionary strDict2 = new StringDictionary();
        strDict2.Add("1", "A");
        strDict2.Add("2", "B");
        strDict2.Add("3", "C");
        strDict2.Add("4", "D");
        strDict2.Add("5", "E");

        Console.WriteLine("\nStringDictionary2 key-value pairs...");
        IEnumerator demoEnum = strDict2.GetEnumerator();
        DictionaryEntry d;
        while (demoEnum.MoveNext()) {
            d = (DictionaryEntry)demoEnum.Current;
            Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
        }
    }
}

ผลลัพธ์ตัวอย่าง 1

StringDictionary1 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
StringDictionary2 key-value pairs...
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E

ตัวอย่าง 2: ใช้ IEnumerator เท่านั้น

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

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

        Console.WriteLine("StringDictionary key-value pairs...");
        IEnumerator demoEnum = strDict.GetEnumerator();
        DictionaryEntry d;
        while (demoEnum.MoveNext()) {
            d = (DictionaryEntry)demoEnum.Current;
            Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
        }
    }
}

ผลลัพธ์ตัวอย่าง 2

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

สรุป

  • GetEnumerator() คืน IEnumerator สำหรับวนซ้ำ
  • foreach ใช้งานง่ายกว่า (ใช้ IEnumerator ด้านใน)
  • คีย์และค่าต้องเป็นสตริงเสมอ