Home >Backend Development >C++ >How Can I Select Random Elements from a Generic List in C#?
Randomly Selecting Items from a C# Generic List
Need to extract several random elements from a list in C#? This is easily achievable regardless of the list's contents (strings, numbers, or custom objects). Here's a concise solution using LINQ.
Suppose you need to select 5 random items from a List<T>
. LINQ provides an elegant approach:
<code class="language-csharp">YourList.OrderBy(x => rnd.Next()).Take(5)</code>
Here, rnd
is a Random
object. This code orders the list based on randomly generated numbers for each element, then selects the first 5. This effectively gives you a random subset of your list.
The above is the detailed content of How Can I Select Random Elements from a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!