Languages
[Edit]
EN

C# / .NET - get random element from HashSet

0 points
Created by:
Pearl-Hurley
559

In this article, we would like to show you how to get random element from HashSet in C#.

 

1. Practical example using foreach loop

Edit

In this example, we generate a random number between 0 and HashSet size. Then using iterator we iterate through the HashSet till we reach the element located at the randomNumber position.

Example output:

2. By converting HashSet to array

Edit

In this example, we convert letters HashSet into an array and then access the random element from it.

Example output:

References

Edit
  1. Random Class (System) | Microsoft Docs
  2. Random.Next Method (System) | Microsoft Docs
  3. List<T>.ToArray Method (System.Collections.Generic) | Microsoft Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join