如何从 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