How to select a random element from a C# list?


Firstly, set a list in C#.

var list = new List<string>{ "one","two","three","four"};

Now get the count of the elements and display randomly.

int index = random.Next(list.Count);
Console.WriteLine(list[index]);

To select a random element from a list in C#, try to run the following code −

Example

 Live Demo

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]);
      }
   }
}

Output

three

Updated on: 23-Jun-2020

36K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements