get a sample of 5 elements from an array in csharp

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.cs
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Create a random number generator
Random rand = new Random();

// Generate 5 unique random indices
int[] indices = Enumerable.Range(0, array.Length)
                          .OrderBy(x => rand.Next())
                          .Take(5)
                          .ToArray();

// Extract the corresponding elements from the array
int[] sample = indices.Select(i => array[i]).ToArray();

// Print the sample
Console.WriteLine(string.Join(", ", sample)); // e.g. "6, 3, 2, 8, 7"
526 chars
17 lines

Explanation:

  • First, we define an array array of 10 integers to sample from.
  • Then, we create a Random instance rand to generate random numbers.
  • To generate 5 unique random indices, we use LINQ to create a sequence of indices from 0 to the length of the array (Enumerable.Range(0, array.Length)), shuffle them (OrderBy(x => rand.Next())), take the first 5 (Take(5)), and convert them to an array (ToArray()).
  • Finally, we use LINQ's 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