如何從 C# 列表中選擇一個隨機元素?
首先,在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP