Home > Backend Development > C++ > How to Efficiently Select Random Elements from a List in C#?

How to Efficiently Select Random Elements from a List in C#?

Linda Hamilton
Release: 2025-01-18 00:41:09
Original
275 people have browsed it

How to Efficiently Select Random Elements from a List in C#?

Randomly Selecting Items from a C# List

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template