Đầu tiên, đặt một danh sách trong C #.
var list = new List<string>{ "one","two","three","four"}; Bây giờ, hãy lấy số lượng các phần tử và hiển thị ngẫu nhiên.
int index = random.Next(list.Count); Console.WriteLine(list[index]);
Để chọn một phần tử ngẫu nhiên từ danh sách trong C #, hãy thử chạy đoạn mã sau -
Ví dụ
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]);
}
}
} Đầu ra
three