[Solved] C# appointing distinct array elements randomly to another array


A simple solution:

int[] card1 = nums.OrderBy(it => Guid.NewGuid()).Take(6).ToArray();

Ordering the original array by a new guid should give you a decent approximation of randomness while avoiding the requirement to explicitly guard against duplication.

Then you just take the first 6 results.

Warning: The random-like behaviour of ordering by guid is an implementation detail of the current Guid.NewGuid() method so it’s important not to rely on this functionality – especially in production code.

A better implementation would use a Fisher-Yates shuffle, see for example, this post: https://stackoverflow.com/a/1653204/5438433

7

solved C# appointing distinct array elements randomly to another array