How to create a random sublist from a list in C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> lst = Enumerable.Range(1, 10).ToList(); 
        Random random = new Random();

        // Shuffle and take a random sublist
        List<int> randomSublist = lst
            .OrderBy(x => random.Next())
            .Take(5) // Specify the size of the sublist
            .ToList();

        Console.WriteLine(string.Join(", ", randomSublist));
    }
}



/*
run:

5, 4, 3, 9, 1

*/

 



answered Jun 20, 2025 by avibootz
edited Jun 20, 2025 by avibootz

Related questions

2 answers 126 views
1 answer 92 views
2 answers 126 views
...