The Challenge:
Efficiently retrieving a predetermined number of random items from a generic list is a common programming task. For example, selecting three random strings from a List<string>
.
A LINQ-Based Solution:
LINQ provides an elegant solution:
<code class="language-csharp">YourList.OrderBy(x => rnd.Next()).Take(3)</code>
Here's a breakdown:
YourList
: Your input list.OrderBy(x => rnd.Next())
: This shuffles the list randomly using a random number generator.rnd
: An instance of the Random
class.Take(3)
: This selects the first three elements from the shuffled list, effectively giving you three random items.This approach creates a new list containing the randomly chosen items.
The above is the detailed content of How to Efficiently Select Random Elements from a List in C#?. For more information, please follow other related articles on the PHP Chinese website!