📜  random.choice c# (1)

📅  最后修改于: 2023-12-03 15:19:42.455000             🧑  作者: Mango

Random.Choice in C#

Introduction

In C#, Random.Choice() is a method that allows developers to randomly select an item from a list of options. This can be useful in a variety of scenarios, such as selecting a random element from a database, picking a random word for a game, and more.

Syntax

The syntax for Random.Choice() is as follows:

public static T Choice<T>(this Random random, IEnumerable<T> source)

In this syntax, T is the type of element in the source list, random is the Random object used for generating random numbers, and source is the list of items to choose from.

Example

Here is an example of using Random.Choice() to select a random integer from an array of integers:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        Random random = new Random();

        int randomInt = random.Choice(numbers);
        Console.WriteLine(randomInt);
    }
}

In this example, we first create an array of integers and a Random object. We then use Random.Choice() to select a random integer from the array, and print the result to the console.

Conclusion

Random.Choice() is a useful method in C# for randomly selecting an item from a list of options. It has a simple syntax and can be used in a variety of scenarios.