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

更新於:23-6-2020

4.2 萬+ 瀏覽量

啟動你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.