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
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.