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

วิธีวนลูป Map ใน C#

C# ไม่มี Map แบบ built-in ใช้ Dictionary แทน

สร้าง Dictionary:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("keyboard", 1);
d.Add("mouse", 2);

ดึง Keys แล้ววนลูป:

var val = d.Keys.ToList();
foreach (var key in val) {
    Console.WriteLine(key);
}

ตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
    static void Main() {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add("keyboard", 1);
        d.Add("mouse", 2);
        var val = d.Keys.ToList();
        val.Sort();
        foreach (var key in val) {
            Console.WriteLine(key);
        }
    }
}

ผลลัพธ์

keyboard
mouse