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?
views:
521answers:
3
+7
A:
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
.
schmrz
2009-09-09 08:00:18
A:
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.
Tony Borf
2009-09-09 11:34:59
+1
A:
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.
Jason
2009-09-09 11:42:07