How to select N random elements from a List<T> in C#

2 Answers

0 votes
/*
 * ============================================================
 * Title: Select N Random Elements from a List<T>
 * ============================================================
 *
 * Description:
 * This program demonstrates how to randomly select N unique
 * elements from a List<T> in C#.
 *
 * Best Practices Used:
 * - Generic method (works with any type)
 * - Input validation
 * - Does not modify the original list
 * - Fisher-Yates shuffle for unbiased randomization
 * - Clear comments and documentation
 * - Exception handling
 *
 * ============================================================
 */

using System;
using System.Collections.Generic;

namespace RandomElementSelection
{
    class Program
    {
        static void Main()
        {
            // Sample data
            List<string> fruits = new List<string>
            {
                "Apple",
                "Banana",
                "Orange",
                "Mango",
                "Grape",
                "Pineapple",
                "Peach",
                "Cherry",
                "Kiwi",
                "Strawberry"
            };

            int numberToSelect = 3;

            try
            {
                // Select random elements
                List<string> selectedItems =
                    GetRandomElements(fruits, numberToSelect);

                Console.WriteLine("Original List:");
                foreach (string fruit in fruits) {
                    Console.WriteLine($"  {fruit}");
                }

                Console.WriteLine();
                Console.WriteLine($"Randomly Selected {numberToSelect} Items:");

                foreach (string item in selectedItems) {
                    Console.WriteLine($"  {item}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        /// <summary>
        /// Returns N unique random elements from a list.
        /// </summary>
        /// <typeparam name="T">The type stored in the list.</typeparam>
        /// <param name="source">Source list.</param>
        /// <param name="count">Number of elements to select.</param>
        /// <returns>A list containing randomly selected elements.</returns>
        private static List<T> GetRandomElements<T>(
            List<T> source,
            int count)
        {
            // Validate input
            if (source == null) {
                throw new ArgumentNullException(nameof(source));
            }

            if (count < 0 || count > source.Count) {
                throw new ArgumentOutOfRangeException(
                    nameof(count),
                    "Count must be between 0 and the number of items in the list.");
            }

            // Create a copy so the original list remains unchanged
            List<T> shuffled = new List<T>(source);

            // Create a Random instance
            Random random = new Random();

            // Fisher-Yates Shuffle
            for (int i = shuffled.Count - 1; i > 0; i--) {
                int j = random.Next(i + 1);

                T temp = shuffled[i];
                shuffled[i] = shuffled[j];
                shuffled[j] = temp;
            }

            // Copy the first N items into the result list
            List<T> result = new List<T>();

            for (int i = 0; i < count; i++) {
                result.Add(shuffled[i]);
            }

            return result;
        }
    }
}


/*
run:

Original List:
  Apple
  Banana
  Orange
  Mango
  Grape
  Pineapple
  Peach
  Cherry
  Kiwi
  Strawberry

Randomly Selected 3 Items:
  Apple
  Orange
  Kiwi

*/

 



answered Oct 9 by avibootz
0 votes
/*
 * ============================================================
 * Title: Select N Random Elements from a List<T>
 * ============================================================
 *
 * Description:
 * This program demonstrates how to randomly select N unique
 * elements from a List<T> in C#.
 *
 * Best Practices Used:
 * - Generic method (works with any type)
 * - Input validation
 * - Does not modify the original list
 * - Fisher-Yates shuffle for unbiased randomization
 * - Clear comments and documentation
 * - Exception handling
 *
 * ============================================================
 */

using System;
using System.Linq;
using System.Collections.Generic;

namespace RandomElementSelection
{
    class Program
    {
        static void Main()
        {
            // Sample data
            List<string> fruits = new List<string>
            {
                "Apple",
                "Banana",
                "Orange",
                "Mango",
                "Grape",
                "Pineapple",
                "Peach",
                "Cherry",
                "Kiwi",
                "Strawberry"
            };

            int numberToSelect = 3;

            try
            {
                // Select random elements
                List<string> selectedItems =
                    GetRandomElements(fruits, numberToSelect);

                Console.WriteLine("Original List:");
                foreach (string fruit in fruits) {
                    Console.WriteLine($"  {fruit}");
                }

                Console.WriteLine();
                Console.WriteLine($"Randomly Selected {numberToSelect} Items:");

                foreach (string item in selectedItems) {
                    Console.WriteLine($"  {item}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        public static List<T> GetRandomElements<T>(List<T> list, int count)
        {
            Random rnd = new Random();

            return list
                    .OrderBy(x => rnd.Next())
                    .Take(count)
                    .ToList();
        }
    }
}


/*
run:

Original List:
  Apple
  Banana
  Orange
  Mango
  Grape
  Pineapple
  Peach
  Cherry
  Kiwi
  Strawberry

Randomly Selected 3 Items:
  Peach
  Orange
  Apple

*/

 



answered Oct 9 by avibootz
...