rajani
rajani

Reputation:

How to randomly select a string

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

Upvotes: 3

Views: 14607

Answers (3)

Jason
Jason

Reputation: 28600

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

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

Usage:

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

The nice thing here is that ElementAt and Count have optimized versions for arrays and List objects, while the algorithm is generalized for use with all finite collection types.

Upvotes: 6

schmrz
schmrz

Reputation: 376

It has been a couple of years (3-4) since I have been programming with C# but isn't this simple & elegant enough:

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

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

Upvotes: 12

Tony Borf
Tony Borf

Reputation: 4660

Try this,

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 pull a value from the array.

Upvotes: 2

Related Questions