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

CsharpProgrammingServer Side Programming

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
raja
Published on 18-Sep-2018 14:00:52
Advertisements