วิธี ToDictionary เป็นวิธีการขยายในภาษา C# และแปลงคอลเลกชันเป็นพจนานุกรม
ขั้นแรก สร้างอาร์เรย์สตริง -
string[] str = new string[] {"Car", "Bus", "Bicycle"}; ตอนนี้ ใช้วิธีพจนานุกรมเพื่อแปลงคอลเล็กชันเป็นพจนานุกรม -
str.ToDictionary(item => item, item => true);
นี่คือรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
string[] str = new string[] {"Car", "Bus", "Bicycle"};
// key and value under ToDictionary
var d = str.ToDictionary(item => item, item => true);
foreach (var ele in d) {
Console.WriteLine("{0}, {1}", ele.Key, ele.Value);
}
}
} ผลลัพธ์
Car, True Bus, True Bicycle, True