ขั้นแรก กำหนดรายการในภาษา C#
var list = new List<string>{ "one","two","three","four"}; ตอนนี้ให้นับองค์ประกอบและแสดงผลแบบสุ่ม
int index = random.Next(list.Count); Console.WriteLine(list[index]);
ในการเลือกองค์ประกอบสุ่มจากรายการใน C# ให้ลองเรียกใช้รหัสต่อไปนี้ -
ตัวอย่าง
using System;
using System.Collections.Generic;
namespace Demo {
class Program {
static void Main(string[] args) {
var random = new Random();
var list = new List<string>{ "one","two","three","four"};
int index = random.Next(list.Count);
Console.WriteLine(list[index]);
}
}
} ผลลัพธ์
three