Quick selection of random element in collection

Wouldn't advise this one in production code but if during testing you need to pull a random element from a pool of known good values you can quickly sort the pool by using

array.OrderBy(arrayElement  => Guid.NewGuid());

To see it in action just try something along the lines of

var range = Enumerable.Range(0, 10);

for(int i = 0 ; i < 10; i++)
    var newArray = range.OrderBy(arrayElement => Guid.NewGuid()).ToArray();
    Console.WriteLine(string.Join(", ", newArray));

Share Tweet Send