Random element of IEnumerable/Array
Random element extension method for IEnumerable/Array
I don't work with random values very often but recently I had to write some small function that returns random value from an array.
It sounded like a good idea to write it as an extension method to make it reusable for other projects.
namespace EnumerationRandom { public static class ExtensionMethods { public static Random random = new Random(); public static T Random<T>(this IEnumerable<T> list) { return list.ToArray().Random(); } public static T Random<T>(this T[] array) { return array[random.Next(0, array.Length - 1)]; } } }
Do not instantiate Random class for every method call, rather use same instance as random seed is time based and if you create Random class instance for every iteration in a loop you will always get the same value. This is only applicable for default parameter-less constructor where you do not force seed value.
The following is a sample console application code for testing methods from above. You can find attached zip file with the same console application project and extension methods.
namespace EnumerationRandom { public static class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "banana", "kiwi", "pomelo", "orange", "apple" }; for (int i = 0; i < 10;i++ ) { Console.WriteLine(fruits.Random()); } Console.ReadLine(); } } }
Code snippets are also available on GitHub so you can favorite them there for future reference you might need.
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article