Home >Backend Development >C++ >How Can I Select Random Elements from a Generic List in C#?

How Can I Select Random Elements from a Generic List in C#?

DDD
DDDOriginal
2025-01-18 00:52:11287browse

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!

Statement:
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