To get a sample of 5 elements from an array in C#, you can use the Random
class to generate random indices and then extract the corresponding elements from the array to create a subarray of length 5. Here's one way to do it:
main.cs526 chars17 lines
Explanation:
array
of 10 integers to sample from.Random
instance rand
to generate random numbers.Enumerable.Range(0, array.Length)
), shuffle them (OrderBy(x => rand.Next())
), take the first 5 (Take(5)
), and convert them to an array (ToArray()
).Select
method to extract the elements from array
at the selected indices and store them in a new array sample
, which we print to the console using string.Join
.gistlibby LogSnag