How to arbitrarily select a row

When I click the button, the line should display as ex output. good morningor good afternoon. How can I use C # to randomly select a string to display?

+3
source share
3 answers

It has been a couple of years (3-4) since I programmed C #, but it is not so simple and elegant enough:

string randomPick(string[] strings)
{
    return strings[random.Next(strings.Length)];
}

You should also check if the input array is not null.

+13
source

You can define an extension method to select any random element IEnumerable(including string arrays):

public static T RandomElement<T>(this IEnumerable<T> coll)
{
    var rnd = new Random();
    return coll.ElementAt(rnd.Next(coll.Count()));
}

Using:

string[] messages = new[] { "good morning", "good afternoon" };
string message = messages.RandomElement();

, ElementAt Count List, .

+6

Try it,

Random random = new Random();
string[] weekDays = new string[] { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
Response.Write(weekDays[random.Next(6)]);

All you need is a string array and a random number to infer the value from the array.

+2
source

Source: https://habr.com/ru/post/1717216/


All Articles